]> sigrok.org Git - libsigrokdecode.git/blob - decoders/spi/pd.py
spi: Refactor code, use a state machine.
[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-2013 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, write to the Free Software
19 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
20 ##
21
22 # SPI protocol decoder
23
24 import sigrokdecode as srd
25
26 # Key: (CPOL, CPHA). Value: SPI mode.
27 # Clock polarity (CPOL) = 0/1: Clock is low/high when inactive.
28 # Clock phase (CPHA) = 0/1: Data is valid on the leading/trailing clock edge.
29 spi_mode = {
30     (0, 0): 0, # Mode 0
31     (0, 1): 1, # Mode 1
32     (1, 0): 2, # Mode 2
33     (1, 1): 3, # Mode 3
34 }
35
36 class Decoder(srd.Decoder):
37     api_version = 1
38     id = 'spi'
39     name = 'SPI'
40     longname = 'Serial Peripheral Interface'
41     desc = 'Full-duplex, synchronous, serial bus.'
42     license = 'gplv2+'
43     inputs = ['logic']
44     outputs = ['spi']
45     probes = [
46         {'id': 'miso', 'name': 'MISO',
47          'desc': 'SPI MISO line (Master in, slave out)'},
48         {'id': 'mosi', 'name': 'MOSI',
49          'desc': 'SPI MOSI line (Master out, slave in)'},
50         {'id': 'sck', 'name': 'CLK', 'desc': 'SPI clock line'},
51         {'id': 'cs', 'name': 'CS#', 'desc': 'SPI CS (chip select) line'},
52     ]
53     optional_probes = [] # TODO
54     options = {
55         'cs_polarity': ['CS# polarity', 'active-low'],
56         'cpol': ['Clock polarity', 0],
57         'cpha': ['Clock phase', 0],
58         'bitorder': ['Bit order within the SPI data', 'msb-first'],
59         'wordsize': ['Word size of SPI data', 8], # 1-64?
60         'format': ['Data format', 'hex'],
61     }
62     annotations = [
63         ['MISO/MOSI data', 'MISO/MOSI SPI data'],
64         ['MISO data', 'MISO SPI data'],
65         ['MOSI data', 'MOSI SPI data'],
66         ['Warnings', 'Human-readable warnings'],
67     ]
68
69     def __init__(self):
70         self.oldsck = 1
71         self.bitcount = 0
72         self.mosidata = 0
73         self.misodata = 0
74         self.bytesreceived = 0
75         self.startsample = -1
76         self.samplenum = -1
77         self.cs_was_deasserted_during_data_word = 0
78         self.oldcs = -1
79         self.oldpins = None
80         self.state = 'IDLE'
81
82     def start(self, metadata):
83         self.out_proto = self.add(srd.OUTPUT_PROTO, 'spi')
84         self.out_ann = self.add(srd.OUTPUT_ANN, 'spi')
85
86     def report(self):
87         return 'SPI: %d bytes received' % self.bytesreceived
88
89     def putpw(self, data):
90         self.put(self.startsample, self.samplenum, self.out_proto, data)
91
92     def putw(self, data):
93         self.put(self.startsample, self.samplenum, self.out_ann, data)
94
95     def handle_bit(self, miso, mosi, sck, cs):
96         # If this is the first bit, save its sample number.
97         if self.bitcount == 0:
98             self.startsample = self.samplenum
99             active_low = (self.options['cs_polarity'] == 'active-low')
100             deasserted = cs if active_low else not cs
101             if deasserted:
102                 self.cs_was_deasserted_during_data_word = 1
103
104         ws = self.options['wordsize']
105
106         # Receive MOSI bit into our shift register.
107         if self.options['bitorder'] == 'msb-first':
108             self.mosidata |= mosi << (ws - 1 - self.bitcount)
109         else:
110             self.mosidata |= mosi << self.bitcount
111
112         # Receive MISO bit into our shift register.
113         if self.options['bitorder'] == 'msb-first':
114             self.misodata |= miso << (ws - 1 - self.bitcount)
115         else:
116             self.misodata |= miso << self.bitcount
117
118         self.bitcount += 1
119
120         # Continue to receive if not enough bits were received, yet.
121         if self.bitcount != ws:
122             return
123
124         self.putpw(['DATA', self.mosidata, self.misodata])
125         self.putw([0, ['%02X/%02X' % (self.mosidata, self.misodata)]])
126         self.putw([1, ['%02X' % self.misodata]])
127         self.putw([2, ['%02X' % self.mosidata]])
128
129         if self.cs_was_deasserted_during_data_word:
130             self.putw([3, ['CS# was deasserted during this data word!']])
131
132         # Reset decoder state.
133         self.mosidata = 0
134         self.misodata = 0
135         self.bitcount = 0
136
137         # Keep stats for summary.
138         self.bytesreceived += 1
139
140     def find_clk_edge(self, miso, mosi, sck, cs):
141         if self.oldcs != cs:
142             # Send all CS# pin value changes.
143             self.put(self.samplenum, self.samplenum, self.out_proto,
144                      ['CS-CHANGE', self.oldcs, cs])
145             self.oldcs = cs
146
147         # Ignore sample if the clock pin hasn't changed.
148         if sck == self.oldsck:
149             return
150
151         self.oldsck = sck
152
153         # Sample data on rising/falling clock edge (depends on mode).
154         mode = spi_mode[self.options['cpol'], self.options['cpha']]
155         if mode == 0 and sck == 0:   # Sample on rising clock edge
156             return
157         elif mode == 1 and sck == 1: # Sample on falling clock edge
158             return
159         elif mode == 2 and sck == 1: # Sample on falling clock edge
160             return
161         elif mode == 3 and sck == 0: # Sample on rising clock edge
162             return
163
164         # Found the correct clock edge, now get the SPI bit(s).
165         self.handle_bit(miso, mosi, sck, cs)
166
167     def decode(self, ss, es, data):
168         # TODO: Either MISO or MOSI could be optional. CS# is optional.
169         for (self.samplenum, pins) in data:
170
171             # Ignore identical samples early on (for performance reasons).
172             if self.oldpins == pins:
173                 continue
174             self.oldpins, (miso, mosi, sck, cs) = pins, pins
175
176             # State machine.
177             if self.state == 'IDLE':
178                 self.find_clk_edge(miso, mosi, sck, cs)
179             else:
180                 raise Exception('Invalid state: %s' % self.state)
181