]> sigrok.org Git - libsigrokdecode.git/blame_incremental - decoders/i2c/pd.py
configure.ac: explicitly require pkg-config related macro
[libsigrokdecode.git] / decoders / i2c / pd.py
... / ...
CommitLineData
1##
2## This file is part of the libsigrokdecode project.
3##
4## Copyright (C) 2010-2016 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, see <http://www.gnu.org/licenses/>.
18##
19
20# TODO: Look into arbitration, collision detection, clock synchronisation, etc.
21# TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
22# TODO: Implement support for detecting various bus errors.
23
24import sigrokdecode as srd
25
26'''
27OUTPUT_PYTHON format:
28
29Packet:
30[<ptype>, <pdata>]
31
32<ptype>:
33 - 'START' (START condition)
34 - 'START REPEAT' (Repeated START condition)
35 - 'ADDRESS READ' (Slave address, read)
36 - 'ADDRESS WRITE' (Slave address, write)
37 - 'DATA READ' (Data, read)
38 - 'DATA WRITE' (Data, write)
39 - 'STOP' (STOP condition)
40 - 'ACK' (ACK bit)
41 - 'NACK' (NACK bit)
42 - 'BITS' (<pdata>: list of data/address bits and their ss/es numbers)
43
44<pdata> is the data or address byte associated with the 'ADDRESS*' and 'DATA*'
45command. Slave addresses do not include bit 0 (the READ/WRITE indication bit).
46For example, a slave address field could be 0x51 (instead of 0xa2).
47For 'START', 'START REPEAT', 'STOP', 'ACK', and 'NACK' <pdata> is None.
48'''
49
50# CMD: [annotation-type-index, long annotation, short annotation]
51proto = {
52 'START': [0, 'Start', 'S'],
53 'START REPEAT': [1, 'Start repeat', 'Sr'],
54 'STOP': [2, 'Stop', 'P'],
55 'ACK': [3, 'ACK', 'A'],
56 'NACK': [4, 'NACK', 'N'],
57 'BIT': [5, 'Bit', 'B'],
58 'ADDRESS READ': [6, 'Address read', 'AR'],
59 'ADDRESS WRITE': [7, 'Address write', 'AW'],
60 'DATA READ': [8, 'Data read', 'DR'],
61 'DATA WRITE': [9, 'Data write', 'DW'],
62}
63
64class SamplerateError(Exception):
65 pass
66
67class Decoder(srd.Decoder):
68 api_version = 3
69 id = 'i2c'
70 name = 'I²C'
71 longname = 'Inter-Integrated Circuit'
72 desc = 'Two-wire, multi-master, serial bus.'
73 license = 'gplv2+'
74 inputs = ['logic']
75 outputs = ['i2c']
76 channels = (
77 {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
78 {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
79 )
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):
110 self.reset()
111
112 def reset(self):
113 self.samplerate = None
114 self.ss = self.es = self.ss_byte = -1
115 self.bitcount = 0
116 self.databyte = 0
117 self.wr = -1
118 self.is_repeat_start = 0
119 self.state = 'FIND START'
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 handle_start(self, pins):
145 self.ss, self.es = self.samplenum, self.samplenum
146 self.pdu_start = self.samplenum
147 self.pdu_bits = 0
148 cmd = 'START REPEAT' if (self.is_repeat_start == 1) else 'START'
149 self.putp([cmd, None])
150 self.putx([proto[cmd][0], proto[cmd][1:]])
151 self.state = 'FIND ADDRESS'
152 self.bitcount = self.databyte = 0
153 self.is_repeat_start = 1
154 self.wr = -1
155 self.bits = []
156
157 # Gather 8 bits of data plus the ACK/NACK bit.
158 def handle_address_or_data(self, pins):
159 scl, sda = pins
160 self.pdu_bits += 1
161
162 # Address and data are transmitted MSB-first.
163 self.databyte <<= 1
164 self.databyte |= sda
165
166 # Remember the start of the first data/address bit.
167 if self.bitcount == 0:
168 self.ss_byte = self.samplenum
169
170 # Store individual bits and their start/end samplenumbers.
171 # In the list, index 0 represents the LSB (I²C transmits MSB-first).
172 self.bits.insert(0, [sda, self.samplenum, self.samplenum])
173 if self.bitcount > 0:
174 self.bits[1][2] = self.samplenum
175 if self.bitcount == 7:
176 self.bitwidth = self.bits[1][2] - self.bits[2][2]
177 self.bits[0][2] += self.bitwidth
178
179 # Return if we haven't collected all 8 + 1 bits, yet.
180 if self.bitcount < 7:
181 self.bitcount += 1
182 return
183
184 d = self.databyte
185 if self.state == 'FIND ADDRESS':
186 # The READ/WRITE bit is only in address bytes, not data bytes.
187 self.wr = 0 if (self.databyte & 1) else 1
188 if self.options['address_format'] == 'shifted':
189 d = d >> 1
190
191 bin_class = -1
192 if self.state == 'FIND ADDRESS' and self.wr == 1:
193 cmd = 'ADDRESS WRITE'
194 bin_class = 1
195 elif self.state == 'FIND ADDRESS' and self.wr == 0:
196 cmd = 'ADDRESS READ'
197 bin_class = 0
198 elif self.state == 'FIND DATA' and self.wr == 1:
199 cmd = 'DATA WRITE'
200 bin_class = 3
201 elif self.state == 'FIND DATA' and self.wr == 0:
202 cmd = 'DATA READ'
203 bin_class = 2
204
205 self.ss, self.es = self.ss_byte, self.samplenum + self.bitwidth
206
207 self.putp(['BITS', self.bits])
208 self.putp([cmd, d])
209
210 self.putb([bin_class, bytes([d])])
211
212 for bit in self.bits:
213 self.put(bit[1], bit[2], self.out_ann, [5, ['%d' % bit[0]]])
214
215 if cmd.startswith('ADDRESS'):
216 self.ss, self.es = self.samplenum, self.samplenum + self.bitwidth
217 w = ['Write', 'Wr', 'W'] if self.wr else ['Read', 'Rd', 'R']
218 self.putx([proto[cmd][0], w])
219 self.ss, self.es = self.ss_byte, self.samplenum
220
221 self.putx([proto[cmd][0], ['%s: %02X' % (proto[cmd][1], d),
222 '%s: %02X' % (proto[cmd][2], d), '%02X' % d]])
223
224 # Done with this packet.
225 self.bitcount = self.databyte = 0
226 self.bits = []
227 self.state = 'FIND ACK'
228
229 def get_ack(self, pins):
230 scl, sda = pins
231 self.ss, self.es = self.samplenum, self.samplenum + self.bitwidth
232 cmd = 'NACK' if (sda == 1) else 'ACK'
233 self.putp([cmd, None])
234 self.putx([proto[cmd][0], proto[cmd][1:]])
235 # There could be multiple data bytes in a row, so either find
236 # another data byte or a STOP condition next.
237 self.state = 'FIND DATA'
238
239 def handle_stop(self, pins):
240 # Meta bitrate
241 elapsed = 1 / float(self.samplerate) * (self.samplenum - self.pdu_start + 1)
242 bitrate = int(1 / elapsed * self.pdu_bits)
243 self.put(self.ss_byte, self.samplenum, self.out_bitrate, bitrate)
244
245 cmd = 'STOP'
246 self.ss, self.es = self.samplenum, self.samplenum
247 self.putp([cmd, None])
248 self.putx([proto[cmd][0], proto[cmd][1:]])
249 self.state = 'FIND START'
250 self.is_repeat_start = 0
251 self.wr = -1
252 self.bits = []
253
254 def decode(self):
255 if not self.samplerate:
256 raise SamplerateError('Cannot decode without samplerate.')
257
258 while True:
259 # State machine.
260 if self.state == 'FIND START':
261 # Wait for a START condition (S): SCL = high, SDA = falling.
262 self.handle_start(self.wait({0: 'h', 1: 'f'}))
263 elif self.state == 'FIND ADDRESS':
264 # Wait for a data bit: SCL = rising.
265 self.handle_address_or_data(self.wait({0: 'r'}))
266 elif self.state == 'FIND DATA':
267 # Wait for any of the following conditions (or combinations):
268 # a) Data sampling of receiver: SCL = rising, and/or
269 # b) START condition (S): SCL = high, SDA = falling, and/or
270 # c) STOP condition (P): SCL = high, SDA = rising
271 pins = self.wait([{0: 'r'}, {0: 'h', 1: 'f'}, {0: 'h', 1: 'r'}])
272
273 # Check which of the condition(s) matched and handle them.
274 if self.matched[0]:
275 self.handle_address_or_data(pins)
276 elif self.matched[1]:
277 self.handle_start(pins)
278 elif self.matched[2]:
279 self.handle_stop(pins)
280 elif self.state == 'FIND ACK':
281 # Wait for a data/ack bit: SCL = rising.
282 self.get_ack(self.wait({0: 'r'}))