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