]> sigrok.org Git - libsigrokdecode.git/blob - decoders/i2c/i2c.py
srd: PDs: Whitespace and cosmetics.
[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 protocol = {
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 # States
54 FIND_START = 0
55 FIND_ADDRESS = 1
56 FIND_DATA = 2
57
58 class Decoder(srd.Decoder):
59     api_version = 1
60     id = 'i2c'
61     name = 'I2C'
62     longname = 'Inter-Integrated Circuit'
63     desc = 'I2C is a two-wire, multi-master, serial bus.'
64     longdesc = '...'
65     license = 'gplv2+'
66     inputs = ['logic']
67     outputs = ['i2c']
68     probes = [
69         {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
70         {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
71     ]
72     optional_probes = []
73     options = {
74         'addressing': ['Slave addressing (in bits)', 7], # 7 or 10
75     }
76     annotations = [
77         # ANN_SHIFTED
78         ['7-bit shifted hex',
79          'Read/write bit shifted out from the 8-bit I2C slave address'],
80         # ANN_SHIFTED_SHORT
81         ['7-bit shifted hex (short)',
82          'Read/write bit shifted out from the 8-bit I2C slave address'],
83         # ANN_RAW
84         ['Raw hex', 'Unaltered raw data'],
85     ]
86
87     def __init__(self, **kwargs):
88         self.startsample = -1
89         self.samplenum = None
90         self.bitcount = 0
91         self.databyte = 0
92         self.wr = -1
93         self.is_repeat_start = 0
94         self.state = FIND_START
95         self.oldscl = None
96         self.oldsda = None
97
98     def start(self, metadata):
99         self.out_proto = self.add(srd.OUTPUT_PROTO, 'i2c')
100         self.out_ann = self.add(srd.OUTPUT_ANN, 'i2c')
101
102     def report(self):
103         pass
104
105     def is_start_condition(self, scl, sda):
106         # START condition (S): SDA = falling, SCL = high
107         if (self.oldsda == 1 and sda == 0) and scl == 1:
108             return True
109         return False
110
111     def is_data_bit(self, scl, sda):
112         # Data sampling of receiver: SCL = rising
113         if self.oldscl == 0 and scl == 1:
114             return True
115         return False
116
117     def is_stop_condition(self, scl, sda):
118         # STOP condition (P): SDA = rising, SCL = high
119         if (self.oldsda == 0 and sda == 1) and scl == 1:
120             return True
121         return False
122
123     def found_start(self, scl, sda):
124         self.startsample = self.samplenum
125
126         cmd = 'START REPEAT' if (self.is_repeat_start == 1) else 'START'
127         self.put(self.out_proto, [cmd, None, None])
128         self.put(self.out_ann, [ANN_SHIFTED, [protocol[cmd][0]]])
129         self.put(self.out_ann, [ANN_SHIFTED_SHORT, [protocol[cmd][1]]])
130
131         self.state = FIND_ADDRESS
132         self.bitcount = self.databyte = 0
133         self.is_repeat_start = 1
134         self.wr = -1
135
136     # Gather 8 bits of data plus the ACK/NACK bit.
137     def found_address_or_data(self, scl, sda):
138         # Address and data are transmitted MSB-first.
139         self.databyte <<= 1
140         self.databyte |= sda
141
142         if self.bitcount == 0:
143             self.startsample = self.samplenum
144
145         # Return if we haven't collected all 8 + 1 bits, yet.
146         self.bitcount += 1
147         if self.bitcount != 9:
148             return
149
150         # Send raw output annotation before we start shifting out
151         # read/write and ack/nack bits.
152         self.put(self.out_ann, [ANN_RAW, ['0x%.2x' % self.databyte]])
153
154         # We received 8 address/data bits and the ACK/NACK bit.
155         self.databyte >>= 1 # Shift out unwanted ACK/NACK bit here.
156
157         if self.state == FIND_ADDRESS:
158             # The READ/WRITE bit is only in address bytes, not data bytes.
159             self.wr = 0 if (self.databyte & 1) else 1
160             d = self.databyte >> 1
161         elif self.state == FIND_DATA:
162             d = self.databyte
163         else:
164             # TODO: Error?
165             pass
166
167         # Last bit that came in was the ACK/NACK bit (1 = NACK).
168         ack_bit = 'NACK' if (sda == 1) else 'ACK'
169
170         if self.state == FIND_ADDRESS and self.wr == 1:
171             cmd = 'ADDRESS WRITE'
172         elif self.state == FIND_ADDRESS and self.wr == 0:
173             cmd = 'ADDRESS READ'
174         elif self.state == FIND_DATA and self.wr == 1:
175             cmd = 'DATA WRITE'
176         elif self.state == FIND_DATA and self.wr == 0:
177             cmd = 'DATA READ'
178
179         self.put(self.out_proto, [cmd, d, ack_bit])
180         self.put(self.out_ann, [ANN_SHIFTED,
181                  [protocol[cmd][0], '0x%02x' % d, protocol[ack_bit][0]]])
182         self.put(self.out_ann, [ANN_SHIFTED_SHORT,
183                  [protocol[cmd][1], '0x%02x' % d, protocol[ack_bit][1]]])
184
185         self.bitcount = self.databyte = 0
186         self.startsample = -1
187
188         if self.state == FIND_ADDRESS:
189             self.state = FIND_DATA
190         elif self.state == FIND_DATA:
191             # There could be multiple data bytes in a row.
192             # So, either find a STOP condition or another data byte next.
193             pass
194
195     def found_stop(self, scl, sda):
196         self.startsample = self.samplenum
197
198         self.put(self.out_proto, ['STOP', None, None])
199         self.put(self.out_ann, [ANN_SHIFTED, [protocol['STOP'][0]]])
200         self.put(self.out_ann, [ANN_SHIFTED_SHORT, [protocol['STOP'][1]]])
201
202         self.state = FIND_START
203         self.is_repeat_start = 0
204         self.wr = -1
205
206     def put(self, output_id, data):
207         # Inject sample range into the call up to sigrok.
208         super(Decoder, self).put(self.startsample, self.samplenum, output_id, data)
209
210     def decode(self, ss, es, data):
211         for samplenum, (scl, sda) in data:
212             self.samplenum = samplenum
213
214             # First sample: Save SCL/SDA value.
215             if self.oldscl == None:
216                 self.oldscl = scl
217                 self.oldsda = sda
218                 continue
219
220             # TODO: Wait until the bus is idle (SDA = SCL = 1) first?
221
222             # State machine.
223             if self.state == FIND_START:
224                 if self.is_start_condition(scl, sda):
225                     self.found_start(scl, sda)
226             elif self.state == FIND_ADDRESS:
227                 if self.is_data_bit(scl, sda):
228                     self.found_address_or_data(scl, sda)
229             elif self.state == FIND_DATA:
230                 if self.is_data_bit(scl, sda):
231                     self.found_address_or_data(scl, sda)
232                 elif self.is_start_condition(scl, sda):
233                     self.found_start(scl, sda)
234                 elif self.is_stop_condition(scl, sda):
235                     self.found_stop(scl, sda)
236             else:
237                 raise Exception('Invalid state %d' % self.STATE)
238
239             # Save current SDA/SCL values for the next round.
240             self.oldscl = scl
241             self.oldsda = sda
242