]> sigrok.org Git - libsigrokdecode.git/blob - decoders/spi/pd.py
spi: Simplify some code chunks.
[libsigrokdecode.git] / decoders / spi / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2011 Gareth McMullin <gareth@blacksphere.co.nz>
5 ## Copyright (C) 2012-2014 Uwe Hermann <uwe@hermann-uwe.de>
6 ##
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
11 ##
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ## GNU General Public License for more details.
16 ##
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
19 ##
20
21 import sigrokdecode as srd
22 from collections import namedtuple
23
24 Data = namedtuple('Data', ['ss', 'es', 'val'])
25
26 '''
27 OUTPUT_PYTHON format:
28
29 Packet:
30 [<ptype>, <data1>, <data2>]
31
32 <ptype>:
33  - 'DATA': <data1> contains the MOSI data, <data2> contains the MISO data.
34    The data is _usually_ 8 bits (but can also be fewer or more bits).
35    Both data items are Python numbers (not strings), or None if the respective
36    channel was not supplied.
37  - 'BITS': <data1>/<data2> contain a list of bit values in this MOSI/MISO data
38    item, and for each of those also their respective start-/endsample numbers.
39  - 'CS-CHANGE': <data1> is the old CS# pin value, <data2> is the new value.
40    Both data items are Python numbers (0/1), not strings. At the beginning of
41    the decoding a packet is generated with <data1> = None and <data2> being the
42    initial state of the CS# pin or None if the chip select pin is not supplied.
43  - 'TRANSFER': <data1>/<data2> contain a list of Data() namedtuples for each
44    byte transferred during this block of CS# asserted time. Each Data() has
45    fields ss, es, and val.
46
47 Examples:
48  ['CS-CHANGE', None, 1]
49  ['CS-CHANGE', 1, 0]
50  ['DATA', 0xff, 0x3a]
51  ['BITS', [[1, 80, 82], [1, 83, 84], [1, 85, 86], [1, 87, 88],
52            [1, 89, 90], [1, 91, 92], [1, 93, 94], [1, 95, 96]],
53           [[0, 80, 82], [1, 83, 84], [0, 85, 86], [1, 87, 88],
54            [1, 89, 90], [1, 91, 92], [0, 93, 94], [0, 95, 96]]]
55  ['DATA', 0x65, 0x00]
56  ['DATA', 0xa8, None]
57  ['DATA', None, 0x55]
58  ['CS-CHANGE', 0, 1]
59  ['TRANSFER', [Data(ss=80, es=96, val=0xff), ...],
60               [Data(ss=80, es=96, val=0x3a), ...]]
61 '''
62
63 # Key: (CPOL, CPHA). Value: SPI mode.
64 # Clock polarity (CPOL) = 0/1: Clock is low/high when inactive.
65 # Clock phase (CPHA) = 0/1: Data is valid on the leading/trailing clock edge.
66 spi_mode = {
67     (0, 0): 0, # Mode 0
68     (0, 1): 1, # Mode 1
69     (1, 0): 2, # Mode 2
70     (1, 1): 3, # Mode 3
71 }
72
73 class ChannelError(Exception):
74     pass
75
76 class Decoder(srd.Decoder):
77     api_version = 3
78     id = 'spi'
79     name = 'SPI'
80     longname = 'Serial Peripheral Interface'
81     desc = 'Full-duplex, synchronous, serial bus.'
82     license = 'gplv2+'
83     inputs = ['logic']
84     outputs = ['spi']
85     channels = (
86         {'id': 'clk', 'name': 'CLK', 'desc': 'Clock'},
87     )
88     optional_channels = (
89         {'id': 'miso', 'name': 'MISO', 'desc': 'Master in, slave out'},
90         {'id': 'mosi', 'name': 'MOSI', 'desc': 'Master out, slave in'},
91         {'id': 'cs', 'name': 'CS#', 'desc': 'Chip-select'},
92     )
93     options = (
94         {'id': 'cs_polarity', 'desc': 'CS# polarity', 'default': 'active-low',
95             'values': ('active-low', 'active-high')},
96         {'id': 'cpol', 'desc': 'Clock polarity', 'default': 0,
97             'values': (0, 1)},
98         {'id': 'cpha', 'desc': 'Clock phase', 'default': 0,
99             'values': (0, 1)},
100         {'id': 'bitorder', 'desc': 'Bit order',
101             'default': 'msb-first', 'values': ('msb-first', 'lsb-first')},
102         {'id': 'wordsize', 'desc': 'Word size', 'default': 8},
103     )
104     annotations = (
105         ('miso-data', 'MISO data'),
106         ('mosi-data', 'MOSI data'),
107         ('miso-bits', 'MISO bits'),
108         ('mosi-bits', 'MOSI bits'),
109         ('warnings', 'Human-readable warnings'),
110     )
111     annotation_rows = (
112         ('miso-data', 'MISO data', (0,)),
113         ('miso-bits', 'MISO bits', (2,)),
114         ('mosi-data', 'MOSI data', (1,)),
115         ('mosi-bits', 'MOSI bits', (3,)),
116         ('other', 'Other', (4,)),
117     )
118     binary = (
119         ('miso', 'MISO'),
120         ('mosi', 'MOSI'),
121     )
122
123     def __init__(self):
124         self.samplerate = None
125         self.bitcount = 0
126         self.misodata = self.mosidata = 0
127         self.misobits = []
128         self.mosibits = []
129         self.misobytes = []
130         self.mosibytes = []
131         self.ss_block = -1
132         self.samplenum = -1
133         self.ss_transfer = -1
134         self.cs_was_deasserted = False
135         self.have_cs = self.have_miso = self.have_mosi = None
136
137     def metadata(self, key, value):
138         if key == srd.SRD_CONF_SAMPLERATE:
139             self.samplerate = value
140
141     def start(self):
142         self.out_python = self.register(srd.OUTPUT_PYTHON)
143         self.out_ann = self.register(srd.OUTPUT_ANN)
144         self.out_binary = self.register(srd.OUTPUT_BINARY)
145         if self.samplerate is not None:
146             self.out_bitrate = self.register(srd.OUTPUT_META,
147                     meta=(int, 'Bitrate', 'Bitrate during transfers'))
148         self.bw = (self.options['wordsize'] + 7) // 8
149
150     def putw(self, data):
151         self.put(self.ss_block, self.samplenum, self.out_ann, data)
152
153     def putdata(self):
154         # Pass MISO and MOSI bits and then data to the next PD up the stack.
155         so = self.misodata if self.have_miso else None
156         si = self.mosidata if self.have_mosi else None
157         so_bits = self.misobits if self.have_miso else None
158         si_bits = self.mosibits if self.have_mosi else None
159
160         if self.have_miso:
161             ss, es = self.misobits[-1][1], self.misobits[0][2]
162             bdata = so.to_bytes(self.bw, byteorder='big')
163             self.put(ss, es, self.out_binary, [0, bdata])
164         if self.have_mosi:
165             ss, es = self.mosibits[-1][1], self.mosibits[0][2]
166             bdata = si.to_bytes(self.bw, byteorder='big')
167             self.put(ss, es, self.out_binary, [1, bdata])
168
169         self.put(ss, es, self.out_python, ['BITS', si_bits, so_bits])
170         self.put(ss, es, self.out_python, ['DATA', si, so])
171
172         if self.have_miso:
173             self.misobytes.append(Data(ss=ss, es=es, val=so))
174         if self.have_mosi:
175             self.mosibytes.append(Data(ss=ss, es=es, val=si))
176
177         # Bit annotations.
178         if self.have_miso:
179             for bit in self.misobits:
180                 self.put(bit[1], bit[2], self.out_ann, [2, ['%d' % bit[0]]])
181         if self.have_mosi:
182             for bit in self.mosibits:
183                 self.put(bit[1], bit[2], self.out_ann, [3, ['%d' % bit[0]]])
184
185         # Dataword annotations.
186         if self.have_miso:
187             self.put(ss, es, self.out_ann, [0, ['%02X' % self.misodata]])
188         if self.have_mosi:
189             self.put(ss, es, self.out_ann, [1, ['%02X' % self.mosidata]])
190
191     def reset_decoder_state(self):
192         self.misodata = 0 if self.have_miso else None
193         self.mosidata = 0 if self.have_mosi else None
194         self.misobits = [] if self.have_miso else None
195         self.mosibits = [] if self.have_mosi else None
196         self.bitcount = 0
197
198     def cs_asserted(self, cs):
199         active_low = (self.options['cs_polarity'] == 'active-low')
200         return (cs == 0) if active_low else (cs == 1)
201
202     def handle_bit(self, miso, mosi, clk, cs):
203         # If this is the first bit of a dataword, save its sample number.
204         if self.bitcount == 0:
205             self.ss_block = self.samplenum
206             self.cs_was_deasserted = \
207                 not self.cs_asserted(cs) if self.have_cs else False
208
209         ws = self.options['wordsize']
210         bo = self.options['bitorder']
211
212         # Receive MISO bit into our shift register.
213         if self.have_miso:
214             if bo == 'msb-first':
215                 self.misodata |= miso << (ws - 1 - self.bitcount)
216             else:
217                 self.misodata |= miso << self.bitcount
218
219         # Receive MOSI bit into our shift register.
220         if self.have_mosi:
221             if bo == 'msb-first':
222                 self.mosidata |= mosi << (ws - 1 - self.bitcount)
223             else:
224                 self.mosidata |= mosi << self.bitcount
225
226         # Guesstimate the endsample for this bit (can be overridden below).
227         es = self.samplenum
228         if self.bitcount > 0:
229             if self.have_miso:
230                 es += self.samplenum - self.misobits[0][1]
231             elif self.have_mosi:
232                 es += self.samplenum - self.mosibits[0][1]
233
234         if self.have_miso:
235             self.misobits.insert(0, [miso, self.samplenum, es])
236         if self.have_mosi:
237             self.mosibits.insert(0, [mosi, self.samplenum, es])
238
239         if self.bitcount > 0 and self.have_miso:
240             self.misobits[1][2] = self.samplenum
241         if self.bitcount > 0 and self.have_mosi:
242             self.mosibits[1][2] = self.samplenum
243
244         self.bitcount += 1
245
246         # Continue to receive if not enough bits were received, yet.
247         if self.bitcount != ws:
248             return
249
250         self.putdata()
251
252         # Meta bitrate.
253         if self.samplerate is not None:
254             elapsed = 1 / float(self.samplerate)
255             elapsed *= (self.samplenum - self.ss_block + 1)
256             bitrate = int(1 / elapsed * ws)
257             self.put(self.ss_block, self.samplenum, self.out_bitrate, bitrate)
258
259         if self.have_cs and self.cs_was_deasserted:
260             self.putw([4, ['CS# was deasserted during this data word!']])
261
262         self.reset_decoder_state()
263
264     def find_clk_edge(self, miso, mosi, clk, cs, first):
265         if self.have_cs and (first or self.matched[self.have_cs]):
266             # Send all CS# pin value changes.
267             oldcs = None if first else 1 - cs
268             self.put(self.samplenum, self.samplenum, self.out_python,
269                      ['CS-CHANGE', oldcs, cs])
270
271             if self.cs_asserted(cs):
272                 self.ss_transfer = self.samplenum
273                 self.misobytes = []
274                 self.mosibytes = []
275             else:
276                 self.put(self.ss_transfer, self.samplenum, self.out_python,
277                     ['TRANSFER', self.mosibytes, self.misobytes])
278
279             # Reset decoder state when CS# changes (and the CS# pin is used).
280             self.reset_decoder_state()
281
282         # We only care about samples if CS# is asserted.
283         if self.have_cs and not self.cs_asserted(cs):
284             return
285
286         # Ignore sample if the clock pin hasn't changed.
287         if first or not self.matched[0]:
288             return
289
290         # Sample data on rising/falling clock edge (depends on mode).
291         mode = spi_mode[self.options['cpol'], self.options['cpha']]
292         if mode == 0 and clk == 0:   # Sample on rising clock edge
293             return
294         elif mode == 1 and clk == 1: # Sample on falling clock edge
295             return
296         elif mode == 2 and clk == 1: # Sample on falling clock edge
297             return
298         elif mode == 3 and clk == 0: # Sample on rising clock edge
299             return
300
301         # Found the correct clock edge, now get the SPI bit(s).
302         self.handle_bit(miso, mosi, clk, cs)
303
304     def decode(self):
305         # The CLK input is mandatory. Other signals are (individually)
306         # optional. Yet either MISO or MOSI (or both) must be provided.
307         # Tell stacked decoders when we don't have a CS# signal.
308         if not self.has_channel(0):
309             raise ChannelError('Either MISO or MOSI (or both) pins required.')
310         self.have_miso = self.has_channel(1)
311         self.have_mosi = self.has_channel(2)
312         if not self.have_miso and not self.have_mosi:
313             raise ChannelError('Either MISO or MOSI (or both) pins required.')
314         self.have_cs = self.has_channel(3)
315         if not self.have_cs:
316             self.put(0, 0, self.out_python, ['CS-CHANGE', None, None])
317
318         # We want all CLK changes. We want all CS changes if CS is used.
319         # Map 'have_cs' from boolean to an integer index. This simplifies
320         # evaluation in other locations.
321         wait_cond = [{0: 'e'}]
322         if self.have_cs:
323             self.have_cs = len(wait_cond)
324             wait_cond.append({3: 'e'})
325
326         # "Pixel compatibility" with the v2 implementation. Grab and
327         # process the very first sample before checking for edges. The
328         # previous implementation did this by seeding old values with
329         # None, which led to an immediate "change" in comparison.
330         (clk, miso, mosi, cs) = self.wait({})
331         self.find_clk_edge(miso, mosi, clk, cs, True)
332
333         while True:
334             (clk, miso, mosi, cs) = self.wait(wait_cond)
335             self.find_clk_edge(miso, mosi, clk, cs, False)