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