]> sigrok.org Git - libsigrokdecode.git/blob - decoders/uart/pd.py
uart: Emit per-bit annotations and OUTPUT_PYTHON data.
[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         'baudrate': ['Baud rate', 115200],
90         'num_data_bits': ['Data bits', 8], # Valid: 5-9.
91         'parity_type': ['Parity type', 'none'],
92         'parity_check': ['Check parity?', 'yes'], # TODO: Bool supported?
93         'num_stop_bits': ['Stop bit(s)', '1'], # String! 0, 0.5, 1, 1.5.
94         'bit_order': ['Bit order', 'lsb-first'],
95         'format': ['Data format', 'ascii'], # ascii/dec/hex/oct/bin
96         # TODO: Options to invert the signal(s).
97     }
98     annotations = [
99         ['rx-data', 'RX data'],
100         ['tx-data', 'TX data'],
101         ['rx-start', 'RX start bits'],
102         ['tx-start', 'TX start bits'],
103         ['rx-parity-ok', 'RX parity OK bits'],
104         ['tx-parity-ok', 'TX parity OK bits'],
105         ['rx-parity-err', 'RX parity error bits'],
106         ['tx-parity-err', 'TX parity error bits'],
107         ['rx-stop', 'RX stop bits'],
108         ['tx-stop', 'TX stop bits'],
109         ['rx-warnings', 'RX warnings'],
110         ['tx-warnings', 'TX warnings'],
111         ['rx-data-bits', 'RX data bits'],
112         ['tx-data-bits', 'TX data bits'],
113     ]
114     annotation_rows = (
115         ('rx-data', 'RX', (0, 2, 4, 6, 8)),
116         ('rx-data-bits', 'RX bits', (12,)),
117         ('rx-warnings', 'RX warnings', (10,)),
118         ('tx-data', 'TX', (1, 3, 5, 7, 9)),
119         ('tx-data-bits', 'TX bits', (13,)),
120         ('tx-warnings', 'TX warnings', (11,)),
121     )
122     binary = (
123         ('rx', 'RX dump'),
124         ('tx', 'TX dump'),
125         ('rxtx', 'RX/TX dump'),
126     )
127
128     def putx(self, rxtx, data):
129         s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
130         self.put(s - halfbit, self.samplenum + halfbit, self.out_ann, data)
131
132     def putpx(self, rxtx, data):
133         s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
134         self.put(s - halfbit, self.samplenum + halfbit, self.out_python, data)
135
136     def putg(self, data):
137         s, halfbit = self.samplenum, int(self.bit_width / 2)
138         self.put(s - halfbit, s + halfbit, self.out_ann, data)
139
140     def putp(self, data):
141         s, halfbit = self.samplenum, int(self.bit_width / 2)
142         self.put(s - halfbit, s + halfbit, self.out_python, data)
143
144     def putbin(self, rxtx, data):
145         s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
146         self.put(s - halfbit, self.samplenum + halfbit, self.out_bin, data)
147
148     def __init__(self, **kwargs):
149         self.samplerate = None
150         self.samplenum = 0
151         self.frame_start = [-1, -1]
152         self.startbit = [-1, -1]
153         self.cur_data_bit = [0, 0]
154         self.databyte = [0, 0]
155         self.paritybit = [-1, -1]
156         self.stopbit1 = [-1, -1]
157         self.startsample = [-1, -1]
158         self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
159         self.oldbit = [1, 1]
160         self.oldpins = [1, 1]
161         self.databits = [[], []]
162
163     def start(self):
164         self.out_python = self.register(srd.OUTPUT_PYTHON)
165         self.out_bin = self.register(srd.OUTPUT_BINARY)
166         self.out_ann = self.register(srd.OUTPUT_ANN)
167
168     def metadata(self, key, value):
169         if key == srd.SRD_CONF_SAMPLERATE:
170             self.samplerate = value;
171             # The width of one UART bit in number of samples.
172             self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
173
174     # Return true if we reached the middle of the desired bit, false otherwise.
175     def reached_bit(self, rxtx, bitnum):
176         # bitpos is the samplenumber which is in the middle of the
177         # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
178         # (if used) or the first stop bit, and so on).
179         bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
180         bitpos += bitnum * self.bit_width
181         if self.samplenum >= bitpos:
182             return True
183         return False
184
185     def reached_bit_last(self, rxtx, bitnum):
186         bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
187         if self.samplenum >= bitpos:
188             return True
189         return False
190
191     def wait_for_start_bit(self, rxtx, old_signal, signal):
192         # The start bit is always 0 (low). As the idle UART (and the stop bit)
193         # level is 1 (high), the beginning of a start bit is a falling edge.
194         if not (old_signal == 1 and signal == 0):
195             return
196
197         # Save the sample number where the start bit begins.
198         self.frame_start[rxtx] = self.samplenum
199
200         self.state[rxtx] = 'GET START BIT'
201
202     def get_start_bit(self, rxtx, signal):
203         # Skip samples until we're in the middle of the start bit.
204         if not self.reached_bit(rxtx, 0):
205             return
206
207         self.startbit[rxtx] = signal
208
209         # The startbit must be 0. If not, we report an error.
210         if self.startbit[rxtx] != 0:
211             self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
212             # TODO: Abort? Ignore rest of the frame?
213
214         self.cur_data_bit[rxtx] = 0
215         self.databyte[rxtx] = 0
216         self.startsample[rxtx] = -1
217
218         self.state[rxtx] = 'GET DATA BITS'
219
220         self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
221         self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
222
223     def get_data_bits(self, rxtx, signal):
224         # Skip samples until we're in the middle of the desired data bit.
225         if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
226             return
227
228         # Save the sample number of the middle of the first data bit.
229         if self.startsample[rxtx] == -1:
230             self.startsample[rxtx] = self.samplenum
231
232         # Get the next data bit in LSB-first or MSB-first fashion.
233         if self.options['bit_order'] == 'lsb-first':
234             self.databyte[rxtx] >>= 1
235             self.databyte[rxtx] |= \
236                 (signal << (self.options['num_data_bits'] - 1))
237         elif self.options['bit_order'] == 'msb-first':
238             self.databyte[rxtx] <<= 1
239             self.databyte[rxtx] |= (signal << 0)
240         else:
241             raise Exception('Invalid bit order value: %s',
242                             self.options['bit_order'])
243
244         self.putg([rxtx + 12, ['%d' % signal]])
245
246         # Store individual data bits and their start/end samplenumbers.
247         s, halfbit = self.samplenum, int(self.bit_width / 2)
248         self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
249
250         # Return here, unless we already received all data bits.
251         if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
252             self.cur_data_bit[rxtx] += 1
253             return
254
255         self.state[rxtx] = 'GET PARITY BIT'
256
257         self.putpx(rxtx, ['DATABITS', rxtx, self.databits[rxtx]])
258         self.putpx(rxtx, ['DATA', rxtx, self.databyte[rxtx]])
259
260         b, f = self.databyte[rxtx], self.options['format']
261         if f == 'ascii':
262             c = chr(b) if b in range(30, 126 + 1) else '[%02X]' % b
263             self.putx(rxtx, [rxtx, [c]])
264         elif f == 'dec':
265             self.putx(rxtx, [rxtx, [str(b)]])
266         elif f == 'hex':
267             self.putx(rxtx, [rxtx, [hex(b)[2:].zfill(2).upper()]])
268         elif f == 'oct':
269             self.putx(rxtx, [rxtx, [oct(b)[2:].zfill(3)]])
270         elif f == 'bin':
271             self.putx(rxtx, [rxtx, [bin(b)[2:].zfill(8)]])
272         else:
273             raise Exception('Invalid data format option: %s' % f)
274
275         self.putbin(rxtx, (rxtx, bytes([b])))
276         self.putbin(rxtx, (2, bytes([b])))
277
278         self.databits = [[], []]
279
280     def get_parity_bit(self, rxtx, signal):
281         # If no parity is used/configured, skip to the next state immediately.
282         if self.options['parity_type'] == 'none':
283             self.state[rxtx] = 'GET STOP BITS'
284             return
285
286         # Skip samples until we're in the middle of the parity bit.
287         if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
288             return
289
290         self.paritybit[rxtx] = signal
291
292         self.state[rxtx] = 'GET STOP BITS'
293
294         if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
295                      self.databyte[rxtx], self.options['num_data_bits']):
296             self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
297             self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
298         else:
299             # TODO: Return expected/actual parity values.
300             self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
301             self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
302
303     # TODO: Currently only supports 1 stop bit.
304     def get_stop_bits(self, rxtx, signal):
305         # Skip samples until we're in the middle of the stop bit(s).
306         skip_parity = 0 if self.options['parity_type'] == 'none' else 1
307         b = self.options['num_data_bits'] + 1 + skip_parity
308         if not self.reached_bit(rxtx, b):
309             return
310
311         self.stopbit1[rxtx] = signal
312
313         # Stop bits must be 1. If not, we report an error.
314         if self.stopbit1[rxtx] != 1:
315             self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
316             self.putg([rxtx + 8, ['Frame error', 'Frame err', 'FE']])
317             # TODO: Abort? Ignore the frame? Other?
318
319         self.state[rxtx] = 'WAIT FOR START BIT'
320
321         self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
322         self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
323
324     def decode(self, ss, es, data):
325         if self.samplerate is None:
326             raise Exception("Cannot decode without samplerate.")
327         for (self.samplenum, pins) in data:
328
329             # Note: Ignoring identical samples here for performance reasons
330             # is not possible for this PD, at least not in the current state.
331             # if self.oldpins == pins:
332             #     continue
333             self.oldpins, (rx, tx) = pins, pins
334
335             # Either RX or TX (but not both) can be omitted.
336             has_pin = [rx in (0, 1), tx in (0, 1)]
337             if has_pin == [False, False]:
338                 raise Exception('Either TX or RX (or both) pins required.')
339
340             # State machine.
341             for rxtx in (RX, TX):
342                 # Don't try to handle RX (or TX) if not supplied.
343                 if not has_pin[rxtx]:
344                     continue
345
346                 signal = rx if (rxtx == RX) else tx
347
348                 if self.state[rxtx] == 'WAIT FOR START BIT':
349                     self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
350                 elif self.state[rxtx] == 'GET START BIT':
351                     self.get_start_bit(rxtx, signal)
352                 elif self.state[rxtx] == 'GET DATA BITS':
353                     self.get_data_bits(rxtx, signal)
354                 elif self.state[rxtx] == 'GET PARITY BIT':
355                     self.get_parity_bit(rxtx, signal)
356                 elif self.state[rxtx] == 'GET STOP BITS':
357                     self.get_stop_bits(rxtx, signal)
358                 else:
359                     raise Exception('Invalid state: %s' % self.state[rxtx])
360
361                 # Save current RX/TX values for the next round.
362                 self.oldbit[rxtx] = signal
363