]> sigrok.org Git - libsigrokdecode.git/blame - decoders/i2c.py
Decoders: Use 4 spaces for indentation as per PEP-8.
[libsigrokdecode.git] / decoders / i2c.py
CommitLineData
0588ed70
UH
1##
2## This file is part of the sigrok project.
3##
4## Copyright (C) 2010 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#
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
42# STOP condition (P): SDA = rising, SCL = high
43#
33e72c54 44# All data bytes on SDA are exactly 8 bits long (transmitted MSB-first).
0588ed70
UH
45# Each byte has to be followed by a 9th ACK/NACK bit. If that bit is low,
46# that indicates an ACK, if it's high that indicates a NACK.
47#
48# After the first START condition, a master sends the device address of the
49# slave it wants to talk to. Slave addresses are 7 bits long (MSB-first).
33e72c54 50# After those 7 bits, a data direction bit is sent. If the bit is low that
0588ed70
UH
51# indicates a WRITE operation, if it's high that indicates a READ operation.
52#
53# Later an optional 10bit slave addressing scheme was added.
54#
55# Documentation:
56# http://www.nxp.com/acrobat/literature/9398/39340011.pdf (v2.1 spec)
57# http://www.nxp.com/acrobat/usermanuals/UM10204_3.pdf (v3 spec)
58# http://en.wikipedia.org/wiki/I2C
59#
60
61# TODO: Look into arbitration, collision detection, clock synchronisation, etc.
62# TODO: Handle clock stretching.
63# TODO: Handle combined messages / repeated START.
64# TODO: Implement support for 7bit and 10bit slave addresses.
65# TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
66# TODO: Implement support for detecting various bus errors.
67
23fb2e12
UH
68#
69# I2C output format:
70#
71# The output consists of a (Python) list of I2C "packets", each of which
72# has an (implicit) index number (its index in the list).
73# Each packet consists of a Python dict with certain key/value pairs.
74#
75# TODO: Make this a list later instead of a dict?
76#
77# 'type': (string)
78# - 'S' (START condition)
79# - 'Sr' (Repeated START)
80# - 'AR' (Address, read)
81# - 'AW' (Address, write)
82# - 'DR' (Data, read)
83# - 'DW' (Data, write)
84# - 'P' (STOP condition)
85# 'range': (tuple of 2 integers, the min/max samplenumber of this range)
86# - (min, max)
87# - min/max can also be identical.
88# 'data': (actual data as integer ???) TODO: This can be very variable...
89# 'ann': (string; additional annotations / comments)
90#
91# Example output:
92# [{'type': 'S', 'range': (150, 160), 'data': None, 'ann': 'Foobar'},
93# {'type': 'AW', 'range': (200, 300), 'data': 0x50, 'ann': 'Slave 4'},
94# {'type': 'DW', 'range': (310, 370), 'data': 0x00, 'ann': 'Init cmd'},
95# {'type': 'AR', 'range': (500, 560), 'data': 0x50, 'ann': 'Get stat'},
96# {'type': 'DR', 'range': (580, 640), 'data': 0xfe, 'ann': 'OK'},
97# {'type': 'P', 'range': (650, 660), 'data': None, 'ann': None}]
98#
99# Possible other events:
100# - Error event in case protocol looks broken:
101# [{'type': 'ERROR', 'range': (min, max),
ad2dc0de 102# 'data': TODO, 'ann': 'This is not a Microchip 24XX64 EEPROM'},
23fb2e12 103# [{'type': 'ERROR', 'range': (min, max),
ad2dc0de 104# 'data': TODO, 'ann': 'TODO'},
23fb2e12
UH
105# - TODO: Make list of possible errors accessible as metadata?
106#
107# TODO: I2C address of slaves.
108# TODO: Handle multiple different I2C devices on same bus
109# -> we need to decode multiple protocols at the same time.
110# TODO: range: Always contiguous? Splitted ranges? Multiple per event?
111#
112
113#
114# I2C input format:
115#
116# signals:
117# [[id, channel, description], ...] # TODO
118#
119# Example:
120# {'id': 'SCL', 'ch': 5, 'desc': 'Serial clock line'}
121# {'id': 'SDA', 'ch': 7, 'desc': 'Serial data line'}
122# ...
123#
124# {'inbuf': [...],
125# 'signals': [{'SCL': }]}
126#
127
922763ab 128def decode(l):
ad2dc0de
UH
129 print(l)
130 sigrok.put(l)
922763ab
KS
131
132def decode2(inbuf):
ad2dc0de 133 """I2C protocol decoder"""
0588ed70 134
ad2dc0de
UH
135 # FIXME: Get the data in the correct format in the first place.
136 inbuf = [ord(x) for x in inbuf]
a156f09e 137
ad2dc0de
UH
138 # FIXME: This should be passed in as metadata, not hardcoded here.
139 metadata = {
140 'numchannels': 8,
141 'signals': {
142 'scl': {'ch': 5, 'name': 'SCL', 'desc': 'Serial clock line'},
143 'sda': {'ch': 7, 'name': 'SDA', 'desc': 'Serial data line'},
144 },
145 }
0588ed70 146
ad2dc0de
UH
147 out = []
148 o = ack = d = ''
149 bitcount = data = 0
150 wr = startsample = -1
151 IDLE, START, ADDRESS, DATA = range(4)
152 state = IDLE
0588ed70 153
ad2dc0de
UH
154 # Get the channel/probe number of the SCL/SDA signals.
155 scl_bit = metadata['signals']['scl']['ch']
156 sda_bit = metadata['signals']['sda']['ch']
0588ed70 157
ad2dc0de
UH
158 # Get SCL/SDA bit values (0/1 for low/high) of the first sample.
159 s = inbuf[0]
160 oldscl = (s & (1 << scl_bit)) >> scl_bit
161 oldsda = (s & (1 << sda_bit)) >> sda_bit
0588ed70 162
ad2dc0de
UH
163 # Loop over all samples.
164 # TODO: Handle LAs with more/less than 8 channels.
165 for samplenum, s in enumerate(inbuf[1:]): # We skip the first byte...
166 # Get SCL/SDA bit values (0/1 for low/high).
167 scl = (s & (1 << scl_bit)) >> scl_bit
168 sda = (s & (1 << sda_bit)) >> sda_bit
0588ed70 169
ad2dc0de 170 # TODO: Wait until the bus is idle (SDA = SCL = 1) first?
0588ed70 171
ad2dc0de
UH
172 # START condition (S): SDA = falling, SCL = high
173 if (oldsda == 1 and sda == 0) and scl == 1:
174 o = {'type': 'S', 'range': (samplenum, samplenum),
175 'data': None, 'ann': None},
176 out.append(o)
177 state = ADDRESS
178 bitcount = data = 0
0588ed70 179
ad2dc0de
UH
180 # Data latching by transmitter: SCL = low
181 elif (scl == 0):
182 pass # TODO
0588ed70 183
ad2dc0de
UH
184 # Data sampling of receiver: SCL = rising
185 elif (oldscl == 0 and scl == 1):
186 if startsample == -1:
187 startsample = samplenum
188 bitcount += 1
0588ed70 189
ad2dc0de
UH
190 # out.append("%d\t\tRECEIVED BIT %d: %d\n" % \
191 # (samplenum, 8 - bitcount, sda))
0588ed70 192
ad2dc0de
UH
193 # Address and data are transmitted MSB-first.
194 data <<= 1
195 data |= sda
0588ed70 196
ad2dc0de
UH
197 if bitcount != 9:
198 continue
0588ed70 199
ad2dc0de
UH
200 # We received 8 address/data bits and the ACK/NACK bit.
201 data >>= 1 # Shift out unwanted ACK/NACK bit here.
202 ack = (sda == 1) and 'N' or 'A'
203 d = (state == ADDRESS) and (data & 0xfe) or data
204 if state == ADDRESS:
205 wr = (data & 1) and 1 or 0
206 state = DATA
207 o = {'type': state,
208 'range': (startsample, samplenum - 1),
209 'data': d, 'ann': None}
210 if state == ADDRESS and wr == 1:
211 o['type'] = 'AW'
212 elif state == ADDRESS and wr == 0:
213 o['type'] = 'AR'
214 elif state == DATA and wr == 1:
215 o['type'] = 'DW'
216 elif state == DATA and wr == 0:
217 o['type'] = 'DR'
218 out.append(o)
219 o = {'type': ack, 'range': (samplenum, samplenum),
220 'data': None, 'ann': None}
221 out.append(o)
222 bitcount = data = startsample = 0
223 startsample = -1
0588ed70 224
ad2dc0de
UH
225 # STOP condition (P): SDA = rising, SCL = high
226 elif (oldsda == 0 and sda == 1) and scl == 1:
227 o = {'type': 'P', 'range': (samplenum, samplenum),
228 'data': None, 'ann': None},
229 out.append(o)
230 state = IDLE
231 wr = -1
0588ed70 232
ad2dc0de
UH
233 # Save current SDA/SCL values for the next round.
234 oldscl = scl
235 oldsda = sda
0588ed70 236
ad2dc0de
UH
237 # FIXME: Just for testing...
238 return str(out)
0588ed70 239
922763ab 240register = {
ad2dc0de
UH
241 'id': 'i2c',
242 'name': 'I2C',
243 'longname': 'Inter-Integrated Circuit (I2C) bus',
244 'desc': 'I2C is a two-wire, multi-master, serial bus.',
245 'longdesc': '...',
246 'author': 'Uwe Hermann',
247 'email': 'uwe@hermann-uwe.de',
248 'license': 'gplv2+',
249 'in': ['logic'],
250 'out': ['i2c'],
251 'probes': [
252 ['scl', 'Serial clock line'],
253 ['sda', 'Serial data line'],
254 ],
255 'options': {
256 'address-space': ['Address space (in bits)', 7],
257 },
258 # 'start': start,
259 # 'report': report,
922763ab 260}
0588ed70 261
887d6cfa
UH
262# Use psyco (if available) as it results in huge performance improvements.
263try:
ad2dc0de
UH
264 import psyco
265 psyco.bind(decode)
887d6cfa 266except ImportError:
ad2dc0de 267 pass
887d6cfa 268