]> sigrok.org Git - libsigrokdecode.git/blob - decoders/uart/pd.py
Change PD options to be a tuple of dictionaries.
[libsigrokdecode.git] / decoders / uart / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2011-2014 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, write to the Free Software
18 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19 ##
20
21 import sigrokdecode as srd
22
23 '''
24 OUTPUT_PYTHON format:
25
26 UART packet:
27 [<packet-type>, <rxtx>, <packet-data>]
28
29 This is the list of <packet-type>s and their respective <packet-data>:
30  - 'STARTBIT': The data is the (integer) value of the start bit (0/1).
31  - 'DATA': The data is the (integer) value of the UART data. Valid values
32    range from 0 to 512 (as the data can be up to 9 bits in size).
33  - 'DATABITS': List of data bits and their ss/es numbers.
34  - 'PARITYBIT': The data is the (integer) value of the parity bit (0/1).
35  - 'STOPBIT': The data is the (integer) value of the stop bit (0 or 1).
36  - 'INVALID STARTBIT': The data is the (integer) value of the start bit (0/1).
37  - 'INVALID STOPBIT': The data is the (integer) value of the stop bit (0/1).
38  - 'PARITY ERROR': The data is a tuple with two entries. The first one is
39    the expected parity value, the second is the actual parity value.
40  - TODO: Frame error?
41
42 The <rxtx> field is 0 for RX packets, 1 for TX packets.
43 '''
44
45 # Used for differentiating between the two data directions.
46 RX = 0
47 TX = 1
48
49 # Given a parity type to check (odd, even, zero, one), the value of the
50 # parity bit, the value of the data, and the length of the data (5-9 bits,
51 # usually 8 bits) return True if the parity is correct, False otherwise.
52 # 'none' is _not_ allowed as value for 'parity_type'.
53 def parity_ok(parity_type, parity_bit, data, num_data_bits):
54
55     # Handle easy cases first (parity bit is always 1 or 0).
56     if parity_type == 'zero':
57         return parity_bit == 0
58     elif parity_type == 'one':
59         return parity_bit == 1
60
61     # Count number of 1 (high) bits in the data (and the parity bit itself!).
62     ones = bin(data).count('1') + parity_bit
63
64     # Check for odd/even parity.
65     if parity_type == 'odd':
66         return (ones % 2) == 1
67     elif parity_type == 'even':
68         return (ones % 2) == 0
69     else:
70         raise Exception('Invalid parity type: %d' % parity_type)
71
72 class Decoder(srd.Decoder):
73     api_version = 1
74     id = 'uart'
75     name = 'UART'
76     longname = 'Universal Asynchronous Receiver/Transmitter'
77     desc = 'Asynchronous, serial bus.'
78     license = 'gplv2+'
79     inputs = ['logic']
80     outputs = ['uart']
81     probes = []
82     optional_probes = [
83         # Allow specifying only one of the signals, e.g. if only one data
84         # direction exists (or is relevant).
85         {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
86         {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
87     ]
88     options = (
89         {'id': 'baudrate', 'desc': 'Baud rate', 'default': 115200},
90         {'id': 'num_data_bits', 'desc': 'Data bits', 'default': 8,
91             'values': (5, 6, 7, 8, 9)},
92         {'id': 'parity_type', 'desc': 'Parity type', 'default': 'none',
93             'values': ('none', 'odd', 'even', 'zero', 'one')},
94         {'id': 'parity_check', 'desc': 'Check parity?', 'default': 'yes',
95             'values': ('yes', 'no')},
96         {'id': 'num_stop_bits', 'desc': 'Stop bits', 'default': 1.0,
97             'values': (0.0, 0.5, 1.0, 1.5)},
98         {'id': 'bit_order', 'desc': 'Bit order', 'default': 'lsb-first',
99             'values': ('lsb-first', 'msb-first')},
100         {'id': 'format', 'desc': 'Data format', 'default': 'ascii',
101             'values': ('ascii', 'dec', 'hex', 'oct', 'bin')},
102         # TODO: Options to invert the signal(s).
103     )
104     annotations = [
105         ['rx-data', 'RX data'],
106         ['tx-data', 'TX data'],
107         ['rx-start', 'RX start bits'],
108         ['tx-start', 'TX start bits'],
109         ['rx-parity-ok', 'RX parity OK bits'],
110         ['tx-parity-ok', 'TX parity OK bits'],
111         ['rx-parity-err', 'RX parity error bits'],
112         ['tx-parity-err', 'TX parity error bits'],
113         ['rx-stop', 'RX stop bits'],
114         ['tx-stop', 'TX stop bits'],
115         ['rx-warnings', 'RX warnings'],
116         ['tx-warnings', 'TX warnings'],
117         ['rx-data-bits', 'RX data bits'],
118         ['tx-data-bits', 'TX data bits'],
119     ]
120     annotation_rows = (
121         ('rx-data', 'RX', (0, 2, 4, 6, 8)),
122         ('rx-data-bits', 'RX bits', (12,)),
123         ('rx-warnings', 'RX warnings', (10,)),
124         ('tx-data', 'TX', (1, 3, 5, 7, 9)),
125         ('tx-data-bits', 'TX bits', (13,)),
126         ('tx-warnings', 'TX warnings', (11,)),
127     )
128     binary = (
129         ('rx', 'RX dump'),
130         ('tx', 'TX dump'),
131         ('rxtx', 'RX/TX dump'),
132     )
133
134     def putx(self, rxtx, data):
135         s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
136         self.put(s - halfbit, self.samplenum + halfbit, self.out_ann, data)
137
138     def putpx(self, rxtx, data):
139         s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
140         self.put(s - halfbit, self.samplenum + halfbit, self.out_python, data)
141
142     def putg(self, data):
143         s, halfbit = self.samplenum, int(self.bit_width / 2)
144         self.put(s - halfbit, s + halfbit, self.out_ann, data)
145
146     def putp(self, data):
147         s, halfbit = self.samplenum, int(self.bit_width / 2)
148         self.put(s - halfbit, s + halfbit, self.out_python, data)
149
150     def putbin(self, rxtx, data):
151         s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
152         self.put(s - halfbit, self.samplenum + halfbit, self.out_bin, data)
153
154     def __init__(self, **kwargs):
155         self.samplerate = None
156         self.samplenum = 0
157         self.frame_start = [-1, -1]
158         self.startbit = [-1, -1]
159         self.cur_data_bit = [0, 0]
160         self.databyte = [0, 0]
161         self.paritybit = [-1, -1]
162         self.stopbit1 = [-1, -1]
163         self.startsample = [-1, -1]
164         self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
165         self.oldbit = [1, 1]
166         self.oldpins = [1, 1]
167         self.databits = [[], []]
168
169     def start(self):
170         self.out_python = self.register(srd.OUTPUT_PYTHON)
171         self.out_bin = self.register(srd.OUTPUT_BINARY)
172         self.out_ann = self.register(srd.OUTPUT_ANN)
173
174     def metadata(self, key, value):
175         if key == srd.SRD_CONF_SAMPLERATE:
176             self.samplerate = value;
177             # The width of one UART bit in number of samples.
178             self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
179
180     # Return true if we reached the middle of the desired bit, false otherwise.
181     def reached_bit(self, rxtx, bitnum):
182         # bitpos is the samplenumber which is in the middle of the
183         # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
184         # (if used) or the first stop bit, and so on).
185         bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
186         bitpos += bitnum * self.bit_width
187         if self.samplenum >= bitpos:
188             return True
189         return False
190
191     def reached_bit_last(self, rxtx, bitnum):
192         bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
193         if self.samplenum >= bitpos:
194             return True
195         return False
196
197     def wait_for_start_bit(self, rxtx, old_signal, signal):
198         # The start bit is always 0 (low). As the idle UART (and the stop bit)
199         # level is 1 (high), the beginning of a start bit is a falling edge.
200         if not (old_signal == 1 and signal == 0):
201             return
202
203         # Save the sample number where the start bit begins.
204         self.frame_start[rxtx] = self.samplenum
205
206         self.state[rxtx] = 'GET START BIT'
207
208     def get_start_bit(self, rxtx, signal):
209         # Skip samples until we're in the middle of the start bit.
210         if not self.reached_bit(rxtx, 0):
211             return
212
213         self.startbit[rxtx] = signal
214
215         # The startbit must be 0. If not, we report an error.
216         if self.startbit[rxtx] != 0:
217             self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
218             # TODO: Abort? Ignore rest of the frame?
219
220         self.cur_data_bit[rxtx] = 0
221         self.databyte[rxtx] = 0
222         self.startsample[rxtx] = -1
223
224         self.state[rxtx] = 'GET DATA BITS'
225
226         self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
227         self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
228
229     def get_data_bits(self, rxtx, signal):
230         # Skip samples until we're in the middle of the desired data bit.
231         if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
232             return
233
234         # Save the sample number of the middle of the first data bit.
235         if self.startsample[rxtx] == -1:
236             self.startsample[rxtx] = self.samplenum
237
238         # Get the next data bit in LSB-first or MSB-first fashion.
239         if self.options['bit_order'] == 'lsb-first':
240             self.databyte[rxtx] >>= 1
241             self.databyte[rxtx] |= \
242                 (signal << (self.options['num_data_bits'] - 1))
243         elif self.options['bit_order'] == 'msb-first':
244             self.databyte[rxtx] <<= 1
245             self.databyte[rxtx] |= (signal << 0)
246         else:
247             raise Exception('Invalid bit order value: %s',
248                             self.options['bit_order'])
249
250         self.putg([rxtx + 12, ['%d' % signal]])
251
252         # Store individual data bits and their start/end samplenumbers.
253         s, halfbit = self.samplenum, int(self.bit_width / 2)
254         self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
255
256         # Return here, unless we already received all data bits.
257         if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
258             self.cur_data_bit[rxtx] += 1
259             return
260
261         self.state[rxtx] = 'GET PARITY BIT'
262
263         self.putpx(rxtx, ['DATABITS', rxtx, self.databits[rxtx]])
264         self.putpx(rxtx, ['DATA', rxtx, self.databyte[rxtx]])
265
266         b, f = self.databyte[rxtx], self.options['format']
267         if f == 'ascii':
268             c = chr(b) if b in range(30, 126 + 1) else '[%02X]' % b
269             self.putx(rxtx, [rxtx, [c]])
270         elif f == 'dec':
271             self.putx(rxtx, [rxtx, [str(b)]])
272         elif f == 'hex':
273             self.putx(rxtx, [rxtx, [hex(b)[2:].zfill(2).upper()]])
274         elif f == 'oct':
275             self.putx(rxtx, [rxtx, [oct(b)[2:].zfill(3)]])
276         elif f == 'bin':
277             self.putx(rxtx, [rxtx, [bin(b)[2:].zfill(8)]])
278         else:
279             raise Exception('Invalid data format option: %s' % f)
280
281         self.putbin(rxtx, (rxtx, bytes([b])))
282         self.putbin(rxtx, (2, bytes([b])))
283
284         self.databits = [[], []]
285
286     def get_parity_bit(self, rxtx, signal):
287         # If no parity is used/configured, skip to the next state immediately.
288         if self.options['parity_type'] == 'none':
289             self.state[rxtx] = 'GET STOP BITS'
290             return
291
292         # Skip samples until we're in the middle of the parity bit.
293         if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
294             return
295
296         self.paritybit[rxtx] = signal
297
298         self.state[rxtx] = 'GET STOP BITS'
299
300         if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
301                      self.databyte[rxtx], self.options['num_data_bits']):
302             self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
303             self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
304         else:
305             # TODO: Return expected/actual parity values.
306             self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
307             self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
308
309     # TODO: Currently only supports 1 stop bit.
310     def get_stop_bits(self, rxtx, signal):
311         # Skip samples until we're in the middle of the stop bit(s).
312         skip_parity = 0 if self.options['parity_type'] == 'none' else 1
313         b = self.options['num_data_bits'] + 1 + skip_parity
314         if not self.reached_bit(rxtx, b):
315             return
316
317         self.stopbit1[rxtx] = signal
318
319         # Stop bits must be 1. If not, we report an error.
320         if self.stopbit1[rxtx] != 1:
321             self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
322             self.putg([rxtx + 8, ['Frame error', 'Frame err', 'FE']])
323             # TODO: Abort? Ignore the frame? Other?
324
325         self.state[rxtx] = 'WAIT FOR START BIT'
326
327         self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
328         self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
329
330     def decode(self, ss, es, data):
331         if self.samplerate is None:
332             raise Exception("Cannot decode without samplerate.")
333         for (self.samplenum, pins) in data:
334
335             # Note: Ignoring identical samples here for performance reasons
336             # is not possible for this PD, at least not in the current state.
337             # if self.oldpins == pins:
338             #     continue
339             self.oldpins, (rx, tx) = pins, pins
340
341             # Either RX or TX (but not both) can be omitted.
342             has_pin = [rx in (0, 1), tx in (0, 1)]
343             if has_pin == [False, False]:
344                 raise Exception('Either TX or RX (or both) pins required.')
345
346             # State machine.
347             for rxtx in (RX, TX):
348                 # Don't try to handle RX (or TX) if not supplied.
349                 if not has_pin[rxtx]:
350                     continue
351
352                 signal = rx if (rxtx == RX) else tx
353
354                 if self.state[rxtx] == 'WAIT FOR START BIT':
355                     self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
356                 elif self.state[rxtx] == 'GET START BIT':
357                     self.get_start_bit(rxtx, signal)
358                 elif self.state[rxtx] == 'GET DATA BITS':
359                     self.get_data_bits(rxtx, signal)
360                 elif self.state[rxtx] == 'GET PARITY BIT':
361                     self.get_parity_bit(rxtx, signal)
362                 elif self.state[rxtx] == 'GET STOP BITS':
363                     self.get_stop_bits(rxtx, signal)
364                 else:
365                     raise Exception('Invalid state: %s' % self.state[rxtx])
366
367                 # Save current RX/TX values for the next round.
368                 self.oldbit[rxtx] = signal
369