]> sigrok.org Git - libsigrokdecode.git/blob - decoders/i2c/pd.py
Drop obsolete workarounds in PDs.
[libsigrokdecode.git] / decoders / i2c / pd.py
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 10bit slave addresses.
22 # TODO: Implement support for inverting SDA/SCL levels (0->1 and 1->0).
23 # TODO: Implement support for detecting various bus errors.
24
25 import sigrokdecode as srd
26
27 '''
28 OUTPUT_PYTHON format:
29
30 Packet:
31 [<ptype>, <pdata>]
32
33 <ptype>:
34  - 'START' (START condition)
35  - 'START REPEAT' (Repeated START condition)
36  - 'ADDRESS READ' (Slave address, read)
37  - 'ADDRESS WRITE' (Slave address, write)
38  - 'DATA READ' (Data, read)
39  - 'DATA WRITE' (Data, write)
40  - 'STOP' (STOP condition)
41  - 'ACK' (ACK bit)
42  - 'NACK' (NACK bit)
43  - 'BITS' (<pdata>: list of data/address bits and their ss/es numbers)
44
45 <pdata> is the data or address byte associated with the 'ADDRESS*' and 'DATA*'
46 command. Slave addresses do not include bit 0 (the READ/WRITE indication bit).
47 For example, a slave address field could be 0x51 (instead of 0xa2).
48 For 'START', 'START REPEAT', 'STOP', 'ACK', and 'NACK' <pdata> is None.
49 '''
50
51 # CMD: [annotation-type-index, long annotation, short annotation]
52 proto = {
53     'START':           [0, 'Start',         'S'],
54     'START REPEAT':    [1, 'Start repeat',  'Sr'],
55     'STOP':            [2, 'Stop',          'P'],
56     'ACK':             [3, 'ACK',           'A'],
57     'NACK':            [4, 'NACK',          'N'],
58     'BIT':             [5, 'Bit',           'B'],
59     'ADDRESS READ':    [6, 'Address read',  'AR'],
60     'ADDRESS WRITE':   [7, 'Address write', 'AW'],
61     'DATA READ':       [8, 'Data read',     'DR'],
62     'DATA WRITE':      [9, 'Data write',    'DW'],
63 }
64
65 class SamplerateError(Exception):
66     pass
67
68 class Decoder(srd.Decoder):
69     api_version = 3
70     id = 'i2c'
71     name = 'I²C'
72     longname = 'Inter-Integrated Circuit'
73     desc = 'Two-wire, multi-master, serial bus.'
74     license = 'gplv2+'
75     inputs = ['logic']
76     outputs = ['i2c']
77     channels = (
78         {'id': 'scl', 'name': 'SCL', 'desc': 'Serial clock line'},
79         {'id': 'sda', 'name': 'SDA', 'desc': 'Serial data line'},
80     )
81     options = (
82         {'id': 'address_format', 'desc': 'Displayed slave address format',
83             'default': 'shifted', 'values': ('shifted', 'unshifted')},
84     )
85     annotations = (
86         ('start', 'Start condition'),
87         ('repeat-start', 'Repeat start condition'),
88         ('stop', 'Stop condition'),
89         ('ack', 'ACK'),
90         ('nack', 'NACK'),
91         ('bit', 'Data/address bit'),
92         ('address-read', 'Address read'),
93         ('address-write', 'Address write'),
94         ('data-read', 'Data read'),
95         ('data-write', 'Data write'),
96         ('warnings', 'Human-readable warnings'),
97     )
98     annotation_rows = (
99         ('bits', 'Bits', (5,)),
100         ('addr-data', 'Address/Data', (0, 1, 2, 3, 4, 6, 7, 8, 9)),
101         ('warnings', 'Warnings', (10,)),
102     )
103     binary = (
104         ('address-read', 'Address read'),
105         ('address-write', 'Address write'),
106         ('data-read', 'Data read'),
107         ('data-write', 'Data write'),
108     )
109
110     def __init__(self):
111         self.samplerate = None
112         self.ss = self.es = self.ss_byte = -1
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.pdu_start = None
119         self.pdu_bits = 0
120         self.bits = []
121
122     def metadata(self, key, value):
123         if key == srd.SRD_CONF_SAMPLERATE:
124             self.samplerate = value
125
126     def start(self):
127         self.out_python = self.register(srd.OUTPUT_PYTHON)
128         self.out_ann = self.register(srd.OUTPUT_ANN)
129         self.out_binary = self.register(srd.OUTPUT_BINARY)
130         self.out_bitrate = self.register(srd.OUTPUT_META,
131                 meta=(int, 'Bitrate', 'Bitrate from Start bit to Stop bit'))
132
133         # Assume that the initial SCL/SDA pin state is high (logic 1).
134         # This is a good default, since both pins have pullups as per spec.
135         self.initial_pins = [1, 1]
136
137     def putx(self, data):
138         self.put(self.ss, self.es, self.out_ann, data)
139
140     def putp(self, data):
141         self.put(self.ss, self.es, self.out_python, data)
142
143     def putb(self, data):
144         self.put(self.ss, self.es, self.out_binary, data)
145
146     def handle_start(self, pins):
147         self.ss, self.es = self.samplenum, self.samplenum
148         self.pdu_start = self.samplenum
149         self.pdu_bits = 0
150         cmd = 'START REPEAT' if (self.is_repeat_start == 1) else 'START'
151         self.putp([cmd, None])
152         self.putx([proto[cmd][0], proto[cmd][1:]])
153         self.state = 'FIND ADDRESS'
154         self.bitcount = self.databyte = 0
155         self.is_repeat_start = 1
156         self.wr = -1
157         self.bits = []
158
159     # Gather 8 bits of data plus the ACK/NACK bit.
160     def handle_address_or_data(self, pins):
161         scl, sda = pins
162         self.pdu_bits += 1
163
164         # Address and data are transmitted MSB-first.
165         self.databyte <<= 1
166         self.databyte |= sda
167
168         # Remember the start of the first data/address bit.
169         if self.bitcount == 0:
170             self.ss_byte = self.samplenum
171
172         # Store individual bits and their start/end samplenumbers.
173         # In the list, index 0 represents the LSB (I²C transmits MSB-first).
174         self.bits.insert(0, [sda, self.samplenum, self.samplenum])
175         if self.bitcount > 0:
176             self.bits[1][2] = self.samplenum
177         if self.bitcount == 7:
178             self.bitwidth = self.bits[1][2] - self.bits[2][2]
179             self.bits[0][2] += self.bitwidth
180
181         # Return if we haven't collected all 8 + 1 bits, yet.
182         if self.bitcount < 7:
183             self.bitcount += 1
184             return
185
186         d = self.databyte
187         if self.state == 'FIND ADDRESS':
188             # The READ/WRITE bit is only in address bytes, not data bytes.
189             self.wr = 0 if (self.databyte & 1) else 1
190             if self.options['address_format'] == 'shifted':
191                 d = d >> 1
192
193         bin_class = -1
194         if self.state == 'FIND ADDRESS' and self.wr == 1:
195             cmd = 'ADDRESS WRITE'
196             bin_class = 1
197         elif self.state == 'FIND ADDRESS' and self.wr == 0:
198             cmd = 'ADDRESS READ'
199             bin_class = 0
200         elif self.state == 'FIND DATA' and self.wr == 1:
201             cmd = 'DATA WRITE'
202             bin_class = 3
203         elif self.state == 'FIND DATA' and self.wr == 0:
204             cmd = 'DATA READ'
205             bin_class = 2
206
207         self.ss, self.es = self.ss_byte, self.samplenum + self.bitwidth
208
209         self.putp(['BITS', self.bits])
210         self.putp([cmd, d])
211
212         self.putb([bin_class, bytes([d])])
213
214         for bit in self.bits:
215             self.put(bit[1], bit[2], self.out_ann, [5, ['%d' % bit[0]]])
216
217         if cmd.startswith('ADDRESS'):
218             self.ss, self.es = self.samplenum, self.samplenum + self.bitwidth
219             w = ['Write', 'Wr', 'W'] if self.wr else ['Read', 'Rd', 'R']
220             self.putx([proto[cmd][0], w])
221             self.ss, self.es = self.ss_byte, self.samplenum
222
223         self.putx([proto[cmd][0], ['%s: %02X' % (proto[cmd][1], d),
224                    '%s: %02X' % (proto[cmd][2], d), '%02X' % d]])
225
226         # Done with this packet.
227         self.bitcount = self.databyte = 0
228         self.bits = []
229         self.state = 'FIND ACK'
230
231     def get_ack(self, pins):
232         scl, sda = pins
233         self.ss, self.es = self.samplenum, self.samplenum + self.bitwidth
234         cmd = 'NACK' if (sda == 1) else 'ACK'
235         self.putp([cmd, None])
236         self.putx([proto[cmd][0], proto[cmd][1:]])
237         # There could be multiple data bytes in a row, so either find
238         # another data byte or a STOP condition next.
239         self.state = 'FIND DATA'
240
241     def handle_stop(self, pins):
242         # Meta bitrate
243         elapsed = 1 / float(self.samplerate) * (self.samplenum - self.pdu_start + 1)
244         bitrate = int(1 / elapsed * self.pdu_bits)
245         self.put(self.ss_byte, self.samplenum, self.out_bitrate, bitrate)
246
247         cmd = 'STOP'
248         self.ss, self.es = self.samplenum, self.samplenum
249         self.putp([cmd, None])
250         self.putx([proto[cmd][0], proto[cmd][1:]])
251         self.state = 'FIND START'
252         self.is_repeat_start = 0
253         self.wr = -1
254         self.bits = []
255
256     def decode(self):
257         if not self.samplerate:
258             raise SamplerateError('Cannot decode without samplerate.')
259
260         self.wait({})
261
262         while True:
263             # State machine.
264             if self.state == 'FIND START':
265                 # Wait for a START condition (S): SCL = high, SDA = falling.
266                 self.handle_start(self.wait({0: 'h', 1: 'f'}))
267             elif self.state == 'FIND ADDRESS':
268                 # Wait for a data bit: SCL = rising.
269                 self.handle_address_or_data(self.wait({0: 'r'}))
270             elif self.state == 'FIND DATA':
271                 # Wait for any of the following conditions (or combinations):
272                 #  a) Data sampling of receiver: SCL = rising, and/or
273                 #  b) START condition (S): SCL = high, SDA = falling, and/or
274                 #  c) STOP condition (P): SCL = high, SDA = rising
275                 pins = self.wait([{0: 'r'}, {0: 'h', 1: 'f'}, {0: 'h', 1: 'r'}])
276
277                 # Check which of the condition(s) matched and handle them.
278                 if self.matched[0]:
279                     self.handle_address_or_data(pins)
280                 elif self.matched[1]:
281                     self.handle_start(pins)
282                 elif self.matched[2]:
283                     self.handle_stop(pins)
284             elif self.state == 'FIND ACK':
285                 # Wait for a data/ack bit: SCL = rising.
286                 self.get_ack(self.wait({0: 'r'}))