]> sigrok.org Git - libsigrokdecode.git/blob - decoders/uart/pd.py
uart: Make data format selection a PD option.
[libsigrokdecode.git] / decoders / uart / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2011-2013 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 # UART protocol decoder
22
23 import sigrokdecode as srd
24
25 # Used for differentiating between the two data directions.
26 RX = 0
27 TX = 1
28
29 # Given a parity type to check (odd, even, zero, one), the value of the
30 # parity bit, the value of the data, and the length of the data (5-9 bits,
31 # usually 8 bits) return True if the parity is correct, False otherwise.
32 # 'none' is _not_ allowed as value for 'parity_type'.
33 def parity_ok(parity_type, parity_bit, data, num_data_bits):
34
35     # Handle easy cases first (parity bit is always 1 or 0).
36     if parity_type == 'zero':
37         return parity_bit == 0
38     elif parity_type == 'one':
39         return parity_bit == 1
40
41     # Count number of 1 (high) bits in the data (and the parity bit itself!).
42     ones = bin(data).count('1') + parity_bit
43
44     # Check for odd/even parity.
45     if parity_type == 'odd':
46         return (ones % 2) == 1
47     elif parity_type == 'even':
48         return (ones % 2) == 0
49     else:
50         raise Exception('Invalid parity type: %d' % parity_type)
51
52 class Decoder(srd.Decoder):
53     api_version = 1
54     id = 'uart'
55     name = 'UART'
56     longname = 'Universal Asynchronous Receiver/Transmitter'
57     desc = 'Asynchronous, serial bus.'
58     license = 'gplv2+'
59     inputs = ['logic']
60     outputs = ['uart']
61     probes = [
62         # Allow specifying only one of the signals, e.g. if only one data
63         # direction exists (or is relevant).
64         {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
65         {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
66     ]
67     optional_probes = []
68     options = {
69         'baudrate': ['Baud rate', 115200],
70         'num_data_bits': ['Data bits', 8], # Valid: 5-9.
71         'parity_type': ['Parity type', 'none'],
72         'parity_check': ['Check parity?', 'yes'], # TODO: Bool supported?
73         'num_stop_bits': ['Stop bit(s)', '1'], # String! 0, 0.5, 1, 1.5.
74         'bit_order': ['Bit order', 'lsb-first'],
75         'format': ['Data format', 'ascii'], # ascii/dec/hex/oct/bin
76         # TODO: Options to invert the signal(s).
77     }
78     annotations = [
79         ['Data', 'UART data'],
80     ]
81
82     def putx(self, rxtx, data):
83         s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
84         self.put(s - halfbit, self.samplenum + halfbit, self.out_ann, data)
85
86     def putg(self, data):
87         s, halfbit = self.samplenum, int(self.bit_width / 2)
88         self.put(s - halfbit, s + halfbit, self.out_ann, data)
89
90     def putp(self, data):
91         s, halfbit = self.samplenum, int(self.bit_width / 2)
92         self.put(s - halfbit, s + halfbit, self.out_proto, data)
93
94     def __init__(self, **kwargs):
95         self.samplenum = 0
96         self.frame_start = [-1, -1]
97         self.startbit = [-1, -1]
98         self.cur_data_bit = [0, 0]
99         self.databyte = [0, 0]
100         self.paritybit = [-1, -1]
101         self.stopbit1 = [-1, -1]
102         self.startsample = [-1, -1]
103         self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
104         self.oldbit = [1, 1]
105         self.oldpins = [1, 1]
106
107     def start(self, metadata):
108         self.samplerate = metadata['samplerate']
109         self.out_proto = self.add(srd.OUTPUT_PROTO, 'uart')
110         self.out_ann = self.add(srd.OUTPUT_ANN, 'uart')
111
112         # The width of one UART bit in number of samples.
113         self.bit_width = \
114             float(self.samplerate) / float(self.options['baudrate'])
115
116     def report(self):
117         pass
118
119     # Return true if we reached the middle of the desired bit, false otherwise.
120     def reached_bit(self, rxtx, bitnum):
121         # bitpos is the samplenumber which is in the middle of the
122         # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
123         # (if used) or the first stop bit, and so on).
124         bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
125         bitpos += bitnum * self.bit_width
126         if self.samplenum >= bitpos:
127             return True
128         return False
129
130     def reached_bit_last(self, rxtx, bitnum):
131         bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
132         if self.samplenum >= bitpos:
133             return True
134         return False
135
136     def wait_for_start_bit(self, rxtx, old_signal, signal):
137         # The start bit is always 0 (low). As the idle UART (and the stop bit)
138         # level is 1 (high), the beginning of a start bit is a falling edge.
139         if not (old_signal == 1 and signal == 0):
140             return
141
142         # Save the sample number where the start bit begins.
143         self.frame_start[rxtx] = self.samplenum
144
145         self.state[rxtx] = 'GET START BIT'
146
147     def get_start_bit(self, rxtx, signal):
148         # Skip samples until we're in the middle of the start bit.
149         if not self.reached_bit(rxtx, 0):
150             return
151
152         self.startbit[rxtx] = signal
153
154         # The startbit must be 0. If not, we report an error.
155         if self.startbit[rxtx] != 0:
156             self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
157             # TODO: Abort? Ignore rest of the frame?
158
159         self.cur_data_bit[rxtx] = 0
160         self.databyte[rxtx] = 0
161         self.startsample[rxtx] = -1
162
163         self.state[rxtx] = 'GET DATA BITS'
164
165         self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
166         self.putg([0, ['Start bit', 'Start', 'S']])
167
168     def get_data_bits(self, rxtx, signal):
169         # Skip samples until we're in the middle of the desired data bit.
170         if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
171             return
172
173         # Save the sample number of the middle of the first data bit.
174         if self.startsample[rxtx] == -1:
175             self.startsample[rxtx] = self.samplenum
176
177         # Get the next data bit in LSB-first or MSB-first fashion.
178         if self.options['bit_order'] == 'lsb-first':
179             self.databyte[rxtx] >>= 1
180             self.databyte[rxtx] |= \
181                 (signal << (self.options['num_data_bits'] - 1))
182         elif self.options['bit_order'] == 'msb-first':
183             self.databyte[rxtx] <<= 1
184             self.databyte[rxtx] |= (signal << 0)
185         else:
186             raise Exception('Invalid bit order value: %s',
187                             self.options['bit_order'])
188
189         # Return here, unless we already received all data bits.
190         if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
191             self.cur_data_bit[rxtx] += 1
192             return
193
194         self.state[rxtx] = 'GET PARITY BIT'
195
196         self.putp(['DATA', rxtx, self.databyte[rxtx]])
197
198         s = 'RX: ' if (rxtx == RX) else 'TX: '
199         b, f = self.databyte[rxtx], self.options['format']
200         if f == 'ascii':
201             self.putx(rxtx, [0, [s + chr(b)]])
202         elif f == 'dec':
203             self.putx(rxtx, [0, [s + str(b)]])
204         elif f == 'hex':
205             self.putx(rxtx, [0, [s + hex(b)[2:]]])
206         elif f == 'oct':
207             self.putx(rxtx, [0, [s + oct(b)[2:]]])
208         elif f == 'bin':
209             self.putx(rxtx, [0, [s + bin(b)[2:]]])
210         else:
211             raise Exception('Invalid data format option: %s' % f)
212
213     def get_parity_bit(self, rxtx, signal):
214         # If no parity is used/configured, skip to the next state immediately.
215         if self.options['parity_type'] == 'none':
216             self.state[rxtx] = 'GET STOP BITS'
217             return
218
219         # Skip samples until we're in the middle of the parity bit.
220         if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
221             return
222
223         self.paritybit[rxtx] = signal
224
225         self.state[rxtx] = 'GET STOP BITS'
226
227         if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
228                      self.databyte[rxtx], self.options['num_data_bits']):
229             self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
230             self.putg([0, ['Parity bit', 'Parity', 'P']])
231         else:
232             # TODO: Return expected/actual parity values.
233             self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
234             self.putg([0, ['Parity error', 'Parity err', 'PE']])
235
236     # TODO: Currently only supports 1 stop bit.
237     def get_stop_bits(self, rxtx, signal):
238         # Skip samples until we're in the middle of the stop bit(s).
239         skip_parity = 0 if self.options['parity_type'] == 'none' else 1
240         b = self.options['num_data_bits'] + 1 + skip_parity
241         if not self.reached_bit(rxtx, b):
242             return
243
244         self.stopbit1[rxtx] = signal
245
246         # Stop bits must be 1. If not, we report an error.
247         if self.stopbit1[rxtx] != 1:
248             self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
249             # TODO: Abort? Ignore the frame? Other?
250
251         self.state[rxtx] = 'WAIT FOR START BIT'
252
253         self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
254         self.putg([0, ['Stop bit', 'Stop', 'T']])
255
256     def decode(self, ss, es, data):
257         # TODO: Either RX or TX could be omitted (optional probe).
258         for (self.samplenum, pins) in data:
259
260             # Note: Ignoring identical samples here for performance reasons
261             # is not possible for this PD, at least not in the current state.
262             # if self.oldpins == pins:
263             #     continue
264             self.oldpins, (rx, tx) = pins, pins
265
266             # State machine.
267             for rxtx in (RX, TX):
268                 signal = rx if (rxtx == RX) else tx
269
270                 if self.state[rxtx] == 'WAIT FOR START BIT':
271                     self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
272                 elif self.state[rxtx] == 'GET START BIT':
273                     self.get_start_bit(rxtx, signal)
274                 elif self.state[rxtx] == 'GET DATA BITS':
275                     self.get_data_bits(rxtx, signal)
276                 elif self.state[rxtx] == 'GET PARITY BIT':
277                     self.get_parity_bit(rxtx, signal)
278                 elif self.state[rxtx] == 'GET STOP BITS':
279                     self.get_stop_bits(rxtx, signal)
280                 else:
281                     raise Exception('Invalid state: %s' % self.state[rxtx])
282
283                 # Save current RX/TX values for the next round.
284                 self.oldbit[rxtx] = signal
285