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