]> sigrok.org Git - libsigrokdecode.git/blame - decoders/i2c.py
Stacked protocol decoders implementation.
[libsigrokdecode.git] / decoders / i2c.py
CommitLineData
0588ed70
UH
1##
2## This file is part of the sigrok project.
3##
7b86f0bc 4## Copyright (C) 2010-2011 Uwe Hermann <uwe@hermann-uwe.de>
0588ed70
UH
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
7b86f0bc 42# Data bit sampling: SCL = rising
0588ed70
UH
43# STOP condition (P): SDA = rising, SCL = high
44#
33e72c54 45# All data bytes on SDA are exactly 8 bits long (transmitted MSB-first).
0588ed70
UH
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).
33e72c54 51# After those 7 bits, a data direction bit is sent. If the bit is low that
0588ed70
UH
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.
23fb2e12
UH
68# TODO: I2C address of slaves.
69# TODO: Handle multiple different I2C devices on same bus
70# -> we need to decode multiple protocols at the same time.
23fb2e12
UH
71
72#
7ce7775c
BV
73# I2C protocol output format:
74#
75# The protocol output consists of a (Python) list of I2C "packets", each of
76# which is of the form
77#
78# [ _i2c_command_, _data_, _ack_bit_ ]
79#
80# _i2c_command_ is one of:
81# - 'START' (START condition)
82# - 'START_REPEAT' (Repeated START)
83# - 'ADDRESS_READ' (Address, read)
84# - 'ADDRESS_WRITE' (Address, write)
85# - 'DATA_READ' (Data, read)
86# - 'DATA_WRITE' (Data, write)
87# - 'STOP' (STOP condition)
23fb2e12 88#
7ce7775c
BV
89# _data_ is the data or address byte associated with the ADDRESS_* and DATA_*
90# command. For START, START_REPEAT and STOP, this is None.
23fb2e12 91#
7ce7775c 92# _ack_bit_ is either 'ACK' or 'NACK', but may also be None.
23fb2e12 93#
23fb2e12
UH
94#
95
bc5f5a43 96import sigrokdecode
b2c19614 97
7ce7775c
BV
98# annotation feed formats
99ANN_SHIFTED = 0
100ANN_SHIFTED_SHORT = 1
101ANN_RAW = 2
102
15969949
BV
103# values are verbose and short annotation, respectively
104protocol = {
105 'START': ['START', 'S'],
106 'START_REPEAT': ['START REPEAT', 'Sr'],
107 'STOP': ['STOP', 'P'],
108 'ACK': ['ACK', 'A'],
109 'NACK': ['NACK', 'N'],
110 'ADDRESS_READ': ['ADDRESS READ', 'AR'],
111 'ADDRESS_WRITE': ['ADDRESS WRITE','AW'],
112 'DATA_READ': ['DATA READ', 'DR'],
113 'DATA_WRITE': ['DATA WRITE', 'DW'],
114}
e5080882 115
400f9ae7
UH
116# States
117FIND_START = 0
118FIND_ADDRESS = 1
119FIND_DATA = 2
120
f39d2404 121
bc5f5a43 122class Decoder(sigrokdecode.Decoder):
67e847fd 123 id = 'i2c'
f39d2404
UH
124 name = 'I2C'
125 longname = 'Inter-Integrated Circuit (I2C) bus'
126 desc = 'I2C is a two-wire, multi-master, serial bus.'
127 longdesc = '...'
128 author = 'Uwe Hermann'
129 email = 'uwe@hermann-uwe.de'
130 license = 'gplv2+'
131 inputs = ['logic']
132 outputs = ['i2c']
bc5f5a43
BV
133 probes = [
134 {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
135 {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
136 ]
f39d2404
UH
137 options = {
138 'address-space': ['Address space (in bits)', 7],
ad2dc0de 139 }
15969949
BV
140 annotation = [
141 # ANN_SHIFTED
142 ["7-bit shifted hex",
143 "Read/Write bit shifted out from the 8-bit i2c slave address"],
144 # ANN_SHIFTED_SHORT
145 ["7-bit shifted hex (short)",
146 "Read/Write bit shifted out from the 8-bit i2c slave address"],
147 # ANN_RAW
148 ["Raw hex", "Unaltered raw data"]
149 ]
0588ed70 150
3643fc3f 151 def __init__(self, **kwargs):
e5080882
BV
152 self.output_protocol = None
153 self.output_annotation = None
bc5f5a43 154 self.samplecnt = 0
f39d2404
UH
155 self.bitcount = 0
156 self.databyte = 0
157 self.wr = -1
158 self.startsample = -1
5dd9af5b 159 self.is_repeat_start = 0
400f9ae7 160 self.state = FIND_START
f39d2404
UH
161 self.oldscl = None
162 self.oldsda = None
163
3643fc3f 164 def start(self, metadata):
f9a3947a
BV
165 self.output_protocol = self.add(sigrokdecode.SRD_OUTPUT_PROTOCOL, 'i2c')
166 self.output_annotation = self.add(sigrokdecode.SRD_OUTPUT_ANNOTATION, 'i2c')
3643fc3f 167
f39d2404
UH
168 def report(self):
169 pass
170
7b86f0bc 171 def is_start_condition(self, scl, sda):
c4262fd6 172 """START condition (S): SDA = falling, SCL = high"""
7b86f0bc
UH
173 if (self.oldsda == 1 and sda == 0) and scl == 1:
174 return True
175 return False
176
177 def is_data_bit(self, scl, sda):
c4262fd6 178 """Data sampling of receiver: SCL = rising"""
7b86f0bc
UH
179 if self.oldscl == 0 and scl == 1:
180 return True
181 return False
182
183 def is_stop_condition(self, scl, sda):
c4262fd6 184 """STOP condition (P): SDA = rising, SCL = high"""
7b86f0bc
UH
185 if (self.oldsda == 0 and sda == 1) and scl == 1:
186 return True
187 return False
188
e5080882
BV
189 def found_start(self, scl, sda):
190 if self.is_repeat_start == 1:
15969949 191 cmd = 'START_REPEAT'
e5080882 192 else:
15969949 193 cmd = 'START'
7ce7775c 194 self.put(self.output_protocol, [ cmd, None, None ])
15969949
BV
195 self.put(self.output_annotation, [ ANN_SHIFTED, [protocol[cmd][0]] ])
196 self.put(self.output_annotation, [ ANN_SHIFTED_SHORT, [protocol[cmd][1]] ])
e5080882 197
400f9ae7 198 self.state = FIND_ADDRESS
7b86f0bc 199 self.bitcount = self.databyte = 0
5dd9af5b 200 self.is_repeat_start = 1
7b86f0bc 201 self.wr = -1
7b86f0bc 202
e5080882 203 def found_address_or_data(self, scl, sda):
c4262fd6 204 """Gather 8 bits of data plus the ACK/NACK bit."""
7b86f0bc
UH
205
206 if self.startsample == -1:
bc5f5a43
BV
207 # TODO: should be samplenum, as received from the feed
208 self.startsample = self.samplecnt
7b86f0bc
UH
209 self.bitcount += 1
210
211 # Address and data are transmitted MSB-first.
212 self.databyte <<= 1
213 self.databyte |= sda
214
215 # Return if we haven't collected all 8 + 1 bits, yet.
216 if self.bitcount != 9:
217 return []
218
15969949
BV
219 # send raw output annotation before we start shifting out
220 # read/write and ack/nack bits
221 self.put(self.output_annotation, [ANN_RAW, ["0x%.2x" % self.databyte]])
222
7b86f0bc
UH
223 # We received 8 address/data bits and the ACK/NACK bit.
224 self.databyte >>= 1 # Shift out unwanted ACK/NACK bit here.
225
400f9ae7 226 if self.state == FIND_ADDRESS:
7b86f0bc 227 # The READ/WRITE bit is only in address bytes, not data bytes.
84b81f1d
BV
228 if self.databyte & 1:
229 self.wr = 0
230 else:
231 self.wr = 1
232 d = self.databyte >> 1
400f9ae7 233 elif self.state == FIND_DATA:
7b86f0bc
UH
234 d = self.databyte
235 else:
236 # TODO: Error?
237 pass
238
15969949
BV
239 # last bit that came in was the ACK/NACK bit (1 = NACK)
240 if sda == 1:
241 ack_bit = 'NACK'
242 else:
243 ack_bit = 'ACK'
244
7b86f0bc 245 # TODO: Simplify.
400f9ae7 246 if self.state == FIND_ADDRESS and self.wr == 1:
15969949 247 cmd = 'ADDRESS_WRITE'
400f9ae7 248 elif self.state == FIND_ADDRESS and self.wr == 0:
15969949 249 cmd = 'ADDRESS_READ'
400f9ae7 250 elif self.state == FIND_DATA and self.wr == 1:
15969949 251 cmd = 'DATA_WRITE'
400f9ae7 252 elif self.state == FIND_DATA and self.wr == 0:
15969949 253 cmd = 'DATA_READ'
7ce7775c 254 self.put(self.output_protocol, [ cmd, d, ack_bit ] )
15969949
BV
255 self.put(self.output_annotation, [ANN_SHIFTED, [
256 "%s" % protocol[cmd][0],
257 "0x%02x" % d,
258 "%s" % protocol[ack_bit][0]]
259 ] )
260 self.put(self.output_annotation, [ANN_SHIFTED_SHORT, [
261 "%s" % protocol[cmd][1],
262 "0x%02x" % d,
263 "%s" % protocol[ack_bit][1]]
264 ] )
7b86f0bc 265
7b86f0bc
UH
266 self.bitcount = self.databyte = 0
267 self.startsample = -1
268
400f9ae7
UH
269 if self.state == FIND_ADDRESS:
270 self.state = FIND_DATA
271 elif self.state == FIND_DATA:
7b86f0bc
UH
272 # There could be multiple data bytes in a row.
273 # So, either find a STOP condition or another data byte next.
274 pass
275
e5080882 276 def found_stop(self, scl, sda):
7ce7775c 277 self.put(self.output_protocol, [ 'STOP', None, None ])
15969949
BV
278 self.put(self.output_annotation, [ ANN_SHIFTED, [protocol['STOP'][0]] ])
279 self.put(self.output_annotation, [ ANN_SHIFTED_SHORT, [protocol['STOP'][1]] ])
7b86f0bc 280
400f9ae7 281 self.state = FIND_START
5dd9af5b 282 self.is_repeat_start = 0
7b86f0bc
UH
283 self.wr = -1
284
1aef2f93 285 def put(self, output_id, data):
bc5f5a43 286 # inject sample range into the call up to sigrok
15969949 287 # TODO: 0-0 sample range for now
bc5f5a43 288 super(Decoder, self).put(0, 0, output_id, data)
1aef2f93
BV
289
290 def decode(self, timeoffset, duration, data):
bc5f5a43
BV
291 for samplenum, (scl, sda) in data:
292 self.samplecnt += 1
f39d2404
UH
293
294 # First sample: Save SCL/SDA value.
295 if self.oldscl == None:
bc5f5a43
BV
296 self.oldscl = scl
297 self.oldsda = sda
ad2dc0de 298 continue
0588ed70 299
f39d2404
UH
300 # TODO: Wait until the bus is idle (SDA = SCL = 1) first?
301
7b86f0bc 302 # State machine.
400f9ae7 303 if self.state == FIND_START:
7b86f0bc 304 if self.is_start_condition(scl, sda):
e5080882 305 self.found_start(scl, sda)
400f9ae7 306 elif self.state == FIND_ADDRESS:
7b86f0bc 307 if self.is_data_bit(scl, sda):
e5080882 308 self.found_address_or_data(scl, sda)
400f9ae7 309 elif self.state == FIND_DATA:
7b86f0bc 310 if self.is_data_bit(scl, sda):
e5080882 311 self.found_address_or_data(scl, sda)
7b86f0bc 312 elif self.is_start_condition(scl, sda):
e5080882 313 self.found_start(scl, sda)
7b86f0bc 314 elif self.is_stop_condition(scl, sda):
e5080882 315 self.found_stop(scl, sda)
7b86f0bc
UH
316 else:
317 # TODO: Error?
318 pass
f39d2404
UH
319
320 # Save current SDA/SCL values for the next round.
321 self.oldscl = scl
322 self.oldsda = sda
323