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