]> sigrok.org Git - libsigrokdecode.git/blame_incremental - decoders/i2c/pd.py
Change PD options to be a tuple of dictionaries.
[libsigrokdecode.git] / decoders / i2c / pd.py
... / ...
CommitLineData
1##
2## This file is part of the libsigrokdecode project.
3##
4## Copyright (C) 2010-2014 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# TODO: Look into arbitration, collision detection, clock synchronisation, etc.
22# TODO: Implement support for 10bit slave addresses.
23# TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
24# TODO: Implement support for detecting various bus errors.
25
26import sigrokdecode as srd
27
28'''
29OUTPUT_PYTHON format:
30
31I²C packet:
32[<cmd>, <data>]
33
34<cmd> is one of:
35 - 'START' (START condition)
36 - 'START REPEAT' (Repeated START condition)
37 - 'ADDRESS READ' (Slave address, read)
38 - 'ADDRESS WRITE' (Slave address, write)
39 - 'DATA READ' (Data, read)
40 - 'DATA WRITE' (Data, write)
41 - 'STOP' (STOP condition)
42 - 'ACK' (ACK bit)
43 - 'NACK' (NACK bit)
44 - 'BITS' (<data>: list of data/address bits and their ss/es numbers)
45
46<data> is the data or address byte associated with the 'ADDRESS*' and 'DATA*'
47command. Slave addresses do not include bit 0 (the READ/WRITE indication bit).
48For example, a slave address field could be 0x51 (instead of 0xa2).
49For 'START', 'START REPEAT', 'STOP', 'ACK', and 'NACK' <data> is None.
50'''
51
52# CMD: [annotation-type-index, long annotation, short annotation]
53proto = {
54 'START': [0, 'Start', 'S'],
55 'START REPEAT': [1, 'Start repeat', 'Sr'],
56 'STOP': [2, 'Stop', 'P'],
57 'ACK': [3, 'ACK', 'A'],
58 'NACK': [4, 'NACK', 'N'],
59 'BIT': [5, 'Bit', 'B'],
60 'ADDRESS READ': [6, 'Address read', 'AR'],
61 'ADDRESS WRITE': [7, 'Address write', 'AW'],
62 'DATA READ': [8, 'Data read', 'DR'],
63 'DATA WRITE': [9, 'Data write', 'DW'],
64}
65
66class Decoder(srd.Decoder):
67 api_version = 1
68 id = 'i2c'
69 name = 'I²C'
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 {'id': 'address_format', 'desc': 'Displayed slave address format',
82 'default': 'shifted', 'values': ('shifted', 'unshifted')},
83 )
84 annotations = [
85 ['start', 'Start condition'],
86 ['repeat-start', 'Repeat start condition'],
87 ['stop', 'Stop condition'],
88 ['ack', 'ACK'],
89 ['nack', 'NACK'],
90 ['bit', 'Data/address bit'],
91 ['address-read', 'Address read'],
92 ['address-write', 'Address write'],
93 ['data-read', 'Data read'],
94 ['data-write', 'Data write'],
95 ['warnings', 'Human-readable warnings'],
96 ]
97 annotation_rows = (
98 ('bits', 'Bits', (5,)),
99 ('addr-data', 'Address/Data', (0, 1, 2, 3, 4, 6, 7, 8, 9)),
100 ('warnings', 'Warnings', (10,)),
101 )
102 binary = (
103 ('address-read', 'Address read'),
104 ('address-write', 'Address write'),
105 ('data-read', 'Data read'),
106 ('data-write', 'Data write'),
107 )
108
109 def __init__(self, **kwargs):
110 self.samplerate = None
111 self.ss = self.es = self.byte_ss = -1
112 self.samplenum = None
113 self.bitcount = 0
114 self.databyte = 0
115 self.wr = -1
116 self.is_repeat_start = 0
117 self.state = 'FIND START'
118 self.oldscl = self.oldsda = 1
119 self.oldpins = [1, 1]
120 self.pdu_start = None
121 self.pdu_bits = 0
122 self.bits = []
123
124 def metadata(self, key, value):
125 if key == srd.SRD_CONF_SAMPLERATE:
126 self.samplerate = value
127
128 def start(self):
129 self.out_python = self.register(srd.OUTPUT_PYTHON)
130 self.out_ann = self.register(srd.OUTPUT_ANN)
131 self.out_binary = self.register(srd.OUTPUT_BINARY)
132 self.out_bitrate = self.register(srd.OUTPUT_META,
133 meta=(int, 'Bitrate', 'Bitrate from Start bit to Stop bit'))
134
135 def putx(self, data):
136 self.put(self.ss, self.es, self.out_ann, data)
137
138 def putp(self, data):
139 self.put(self.ss, self.es, self.out_python, data)
140
141 def putb(self, data):
142 self.put(self.ss, self.es, self.out_binary, data)
143
144 def is_start_condition(self, scl, sda):
145 # START condition (S): SDA = falling, SCL = high
146 if (self.oldsda == 1 and sda == 0) and scl == 1:
147 return True
148 return False
149
150 def is_data_bit(self, scl, sda):
151 # Data sampling of receiver: SCL = rising
152 if self.oldscl == 0 and scl == 1:
153 return True
154 return False
155
156 def is_stop_condition(self, scl, sda):
157 # STOP condition (P): SDA = rising, SCL = high
158 if (self.oldsda == 0 and sda == 1) and scl == 1:
159 return True
160 return False
161
162 def found_start(self, scl, sda):
163 self.ss, self.es = self.samplenum, self.samplenum
164 self.pdu_start = self.samplenum
165 self.pdu_bits = 0
166 cmd = 'START REPEAT' if (self.is_repeat_start == 1) else 'START'
167 self.putp([cmd, None])
168 self.putx([proto[cmd][0], proto[cmd][1:]])
169 self.state = 'FIND ADDRESS'
170 self.bitcount = self.databyte = 0
171 self.is_repeat_start = 1
172 self.wr = -1
173 self.bits = []
174
175 # Gather 8 bits of data plus the ACK/NACK bit.
176 def found_address_or_data(self, scl, sda):
177 # Address and data are transmitted MSB-first.
178 self.databyte <<= 1
179 self.databyte |= sda
180
181 # Remember the start of the first data/address bit.
182 if self.bitcount == 0:
183 self.byte_ss = self.samplenum
184
185 # Store individual bits and their start/end samplenumbers.
186 # In the list, index 0 represents the LSB (I²C transmits MSB-first).
187 self.bits.insert(0, [sda, self.samplenum, self.samplenum])
188 if self.bitcount > 0:
189 self.bits[1][2] = self.samplenum
190 if self.bitcount == 7:
191 self.bitwidth = self.bits[1][2] - self.bits[2][2]
192 self.bits[0][2] += self.bitwidth
193
194 # Return if we haven't collected all 8 + 1 bits, yet.
195 if self.bitcount < 7:
196 self.bitcount += 1
197 return
198
199 d = self.databyte
200 if self.state == 'FIND ADDRESS':
201 # The READ/WRITE bit is only in address bytes, not data bytes.
202 self.wr = 0 if (self.databyte & 1) else 1
203 if self.options['address_format'] == 'shifted':
204 d = d >> 1
205
206 bin_class = -1
207 if self.state == 'FIND ADDRESS' and self.wr == 1:
208 cmd = 'ADDRESS WRITE'
209 bin_class = 1
210 elif self.state == 'FIND ADDRESS' and self.wr == 0:
211 cmd = 'ADDRESS READ'
212 bin_class = 0
213 elif self.state == 'FIND DATA' and self.wr == 1:
214 cmd = 'DATA WRITE'
215 bin_class = 3
216 elif self.state == 'FIND DATA' and self.wr == 0:
217 cmd = 'DATA READ'
218 bin_class = 2
219
220 self.ss, self.es = self.byte_ss, self.samplenum + self.bitwidth
221
222 self.putp(['BITS', self.bits])
223 self.putp([cmd, d])
224
225 self.putb((bin_class, bytes([d])))
226
227 for bit in self.bits:
228 self.put(bit[1], bit[2], self.out_ann, [5, ['%d' % bit[0]]])
229
230 if cmd.startswith('ADDRESS'):
231 self.ss, self.es = self.samplenum, self.samplenum + self.bitwidth
232 w = ['Write', 'Wr', 'W'] if self.wr else ['Read', 'Rd', 'R']
233 self.putx([proto[cmd][0], w])
234 self.ss, self.es = self.byte_ss, self.samplenum
235
236 self.putx([proto[cmd][0], ['%s: %02X' % (proto[cmd][1], d),
237 '%s: %02X' % (proto[cmd][2], d), '%02X' % d]])
238
239 # Done with this packet.
240 self.bitcount = self.databyte = 0
241 self.bits = []
242 self.state = 'FIND ACK'
243
244 def get_ack(self, scl, sda):
245 self.ss, self.es = self.samplenum, self.samplenum + self.bitwidth
246 cmd = 'NACK' if (sda == 1) else 'ACK'
247 self.putp([cmd, None])
248 self.putx([proto[cmd][0], proto[cmd][1:]])
249 # There could be multiple data bytes in a row, so either find
250 # another data byte or a STOP condition next.
251 self.state = 'FIND DATA'
252
253 def found_stop(self, scl, sda):
254 # Meta bitrate
255 elapsed = 1 / float(self.samplerate) * (self.samplenum - self.pdu_start + 1)
256 bitrate = int(1 / elapsed * self.pdu_bits)
257 self.put(self.byte_ss, self.samplenum, self.out_bitrate, bitrate)
258
259 cmd = 'STOP'
260 self.ss, self.es = self.samplenum, self.samplenum
261 self.putp([cmd, None])
262 self.putx([proto[cmd][0], proto[cmd][1:]])
263 self.state = 'FIND START'
264 self.is_repeat_start = 0
265 self.wr = -1
266 self.bits = []
267
268 def decode(self, ss, es, data):
269 if self.samplerate is None:
270 raise Exception("Cannot decode without samplerate.")
271 for (self.samplenum, pins) in data:
272
273 # Ignore identical samples early on (for performance reasons).
274 if self.oldpins == pins:
275 continue
276 self.oldpins, (scl, sda) = pins, pins
277
278 self.pdu_bits += 1
279
280 # State machine.
281 if self.state == 'FIND START':
282 if self.is_start_condition(scl, sda):
283 self.found_start(scl, sda)
284 elif self.state == 'FIND ADDRESS':
285 if self.is_data_bit(scl, sda):
286 self.found_address_or_data(scl, sda)
287 elif self.state == 'FIND DATA':
288 if self.is_data_bit(scl, sda):
289 self.found_address_or_data(scl, sda)
290 elif self.is_start_condition(scl, sda):
291 self.found_start(scl, sda)
292 elif self.is_stop_condition(scl, sda):
293 self.found_stop(scl, sda)
294 elif self.state == 'FIND ACK':
295 if self.is_data_bit(scl, sda):
296 self.get_ack(scl, sda)
297 else:
298 raise Exception('Invalid state: %s' % self.state)
299
300 # Save current SDA/SCL values for the next round.
301 self.oldscl, self.oldsda = scl, sda
302