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