]> sigrok.org Git - libsigrokdecode.git/blob - decoders/parallel/pd.py
parallel: rephrase word accumulation after reset introduction
[libsigrokdecode.git] / decoders / parallel / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2013-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 import sigrokdecode as srd
21 from common.srdhelper import bitpack
22
23 '''
24 OUTPUT_PYTHON format:
25
26 Packet:
27 [<ptype>, <pdata>]
28
29 <ptype>, <pdata>
30  - 'ITEM', [<item>, <itembitsize>]
31  - 'WORD', [<word>, <wordbitsize>, <worditemcount>]
32
33 <item>:
34  - A single item (a number). It can be of arbitrary size. The max. number
35    of bits in this item is specified in <itembitsize>.
36
37 <itembitsize>:
38  - The size of an item (in bits). For a 4-bit parallel bus this is 4,
39    for a 16-bit parallel bus this is 16, and so on.
40
41 <word>:
42  - A single word (a number). It can be of arbitrary size. The max. number
43    of bits in this word is specified in <wordbitsize>. The (exact) number
44    of items in this word is specified in <worditemcount>.
45
46 <wordbitsize>:
47  - The size of a word (in bits). For a 2-item word with 8-bit items
48    <wordbitsize> is 16, for a 3-item word with 4-bit items <wordbitsize>
49    is 12, and so on.
50
51 <worditemcount>:
52  - The size of a word (in number of items). For a 4-item word (no matter
53    how many bits each item consists of) <worditemcount> is 4, for a 7-item
54    word <worditemcount> is 7, and so on.
55 '''
56
57 NUM_CHANNELS = 8
58
59 class Pin:
60     CLOCK = 0
61     DATA_0 = CLOCK + 1
62     DATA_N = DATA_0 + NUM_CHANNELS
63     # BEWARE! DATA_N points _beyond_ the data partition (Python range(3)
64     # semantics, useful to have to simplify other code locations).
65     RESET = DATA_N
66
67 class Ann:
68     ITEM, WORD, WARN = range(3)
69
70 class ChannelError(Exception):
71     pass
72
73 class Decoder(srd.Decoder):
74     api_version = 3
75     id = 'parallel'
76     name = 'Parallel'
77     longname = 'Parallel sync bus'
78     desc = 'Generic parallel synchronous bus.'
79     license = 'gplv2+'
80     inputs = ['logic']
81     outputs = ['parallel']
82     tags = ['Util']
83     optional_channels = tuple(
84         [{'id': 'clk', 'name': 'CLK', 'desc': 'Clock line'}] +
85         [
86             {'id': 'd%d' % i, 'name': 'D%d' % i, 'desc': 'Data line %d' % i}
87             for i in range(NUM_CHANNELS)
88         ] +
89         [{'id': 'rst', 'name': 'RST', 'desc': 'RESET line'}]
90     )
91     options = (
92         {'id': 'clock_edge', 'desc': 'Clock edge to sample on',
93             'default': 'rising', 'values': ('rising', 'falling', 'either')},
94         {'id': 'reset_polarity', 'desc': 'Reset line polarity',
95             'default': 'low-active', 'values': ('low-active', 'high-active')},
96         {'id': 'wordsize', 'desc': 'Data wordsize (# bus cycles)',
97             'default': 0},
98         {'id': 'endianness', 'desc': 'Data endianness',
99             'default': 'little', 'values': ('little', 'big')},
100     )
101     annotations = (
102         ('item', 'Item'),
103         ('word', 'Word'),
104         ('warning', 'Warning'),
105     )
106     annotation_rows = (
107         ('items', 'Items', (Ann.ITEM,)),
108         ('words', 'Words', (Ann.WORD,)),
109         ('warnings', 'Warnings', (Ann.WARN,)),
110     )
111
112     def __init__(self):
113         self.reset()
114
115     def reset(self):
116         self.pend_item = None
117         self.word_items = []
118
119     def start(self):
120         self.out_python = self.register(srd.OUTPUT_PYTHON)
121         self.out_ann = self.register(srd.OUTPUT_ANN)
122
123     def putg(self, ss, es, ann, txts):
124         self.put(ss, es, self.out_ann, [ann, txts])
125
126     def putpy(self, ss, es, ann, data):
127         self.put(ss, es, self.out_python, [ann, data])
128
129     def flush_word(self, bus_width):
130         if not self.word_items:
131             return
132         word_size = self.options['wordsize']
133
134         items = self.word_items
135         ss, es = items[0][0], items[-1][1]
136         items = [i[2] for i in items]
137         if self.options['endianness'] == 'big':
138             items.reverse()
139         word = sum([d << (i * bus_width) for i, d in enumerate(items)])
140
141         txts = [self.fmt_word.format(word)]
142         self.putg(ss, es, Ann.WORD, txts)
143         self.putpy(ss, es, 'WORD', word)
144         # self.putpy(ss, es, 'WORD', (word, bus_width, word_size))
145
146         if len(items) != word_size:
147             txts = ['incomplete word size', 'word size', 'ws']
148             self.putg(ss, es, Ann.WARN, txts)
149
150         self.word_items.clear()
151
152     def queue_word(self, now, item, bus_width):
153         wordsize = self.options['wordsize']
154         if not wordsize:
155             return
156
157         # Terminate a previously seen item of a word first. Emit the
158         # word's annotation when the last item's end was seen.
159         if self.word_items:
160             ss, _, data = self.word_items[-1]
161             es = now
162             self.word_items[-1] = (ss, es, data)
163             if len(self.word_items) == wordsize:
164                 self.flush_word(bus_width)
165
166         # Start tracking the currently seen item (yet unknown end time).
167         if item is not None:
168             pend = (now, None, item)
169             self.word_items.append(pend)
170
171     def handle_bits(self, now, item, bus_width):
172
173         # Optionally flush a previously started item.
174         if self.pend_item:
175             ss, _, data = self.pend_item
176             self.pend_item = None
177             es = now
178             txts = [self.fmt_item.format(data)]
179             self.putg(ss, es, Ann.ITEM, txts)
180             self.putpy(ss, es, 'ITEM', data)
181             # self.putpy(ss, es, 'ITEM', (data, bus_width))
182
183         # Optionally queue the currently seen item.
184         if item is not None:
185             self.pend_item = (now, None, item)
186
187         # Pass the current item to the word accumulation logic.
188         self.queue_word(now, item, bus_width)
189
190     def decode(self):
191         # Determine which (optional) channels have input data. Insist in
192         # a non-empty input data set. Cope with sparse connection maps.
193         # Store enough state to later "compress" sampled input data.
194         data_indices = [
195             idx if self.has_channel(idx) else None
196             for idx in range(Pin.DATA_0, Pin.DATA_N)
197         ]
198         has_data = [idx for idx in data_indices if idx is not None]
199         if not has_data:
200             raise ChannelError('Need at least one data channel.')
201         max_connected = max(has_data)
202
203         # Pre-determine which input data to strip off, the width of
204         # individual items and multiplexed words, as well as format
205         # strings here. This simplifies call sites which run in tight
206         # loops later.
207         upper_data_bound = max_connected + 1
208         num_item_bits = upper_data_bound - Pin.DATA_0
209         num_word_items = self.options['wordsize']
210         num_word_bits = num_item_bits * num_word_items
211         num_digits = (num_item_bits + 4 - 1) // 4
212         self.fmt_item = "{{:0{}x}}".format(num_digits)
213         num_digits = (num_word_bits + 4 - 1) // 4
214         self.fmt_word = "{{:0{}x}}".format(num_digits)
215
216         # Determine .wait() conditions, depending on the presence of a
217         # clock signal. Either inspect samples on the configured edge of
218         # the clock, or inspect samples upon ANY edge of ANY of the pins
219         # which provide input data.
220         conds = []
221         cond_idx_clock = None
222         cond_idx_data_0 = None
223         cond_idx_data_N = None
224         cond_idx_reset = None
225         has_clock = self.has_channel(Pin.CLOCK)
226         if has_clock:
227             cond_idx_clock = len(conds)
228             edge = {
229                 'rising': 'r',
230                 'falling': 'f',
231                 'either': 'e',
232             }.get(self.options['clock_edge'])
233             conds.append({Pin.CLOCK: edge})
234         else:
235             cond_idx_data_0 = len(conds)
236             conds.extend([{idx: 'e'} for idx in has_data])
237             cond_idx_data_N = len(conds)
238         has_reset = self.has_channel(Pin.RESET)
239         if has_reset:
240             cond_idx_reset = len(conds)
241             conds.append({Pin.RESET: 'e'})
242             reset_active = {
243                 'low-active': 0,
244                 'high-active': 1,
245             }.get(self.options['reset_polarity'])
246
247         # Keep processing the input stream. Assume "always zero" for
248         # not-connected input lines. Pass data bits (all inputs except
249         # clock and reset) to the handle_bits() method. Handle reset
250         # edges first and data changes then, within the same iteration.
251         # This results in robust operation for low-oversampled input.
252         in_reset = False
253         while True:
254             pins = self.wait(conds)
255             clock_edge = cond_idx_clock is not None and self.matched[cond_idx_clock]
256             data_edge = cond_idx_data_0 is not None and [idx for idx in range(cond_idx_data_0, cond_idx_data_N) if self.matched[idx]]
257             reset_edge = cond_idx_reset is not None and self.matched[cond_idx_reset]
258
259             if reset_edge:
260                 in_reset = pins[Pin.RESET] == reset_active
261                 if in_reset:
262                     self.handle_bits(self.samplenum, None, num_item_bits)
263                     self.flush_word(num_item_bits)
264             if in_reset:
265                 continue
266
267             if clock_edge or data_edge:
268                 data_bits = [0 if idx is None else pins[idx] for idx in data_indices]
269                 data_bits = data_bits[:num_item_bits]
270                 item = bitpack(data_bits)
271                 self.handle_bits(self.samplenum, item, num_item_bits)