2 ## This file is part of the sigrok project.
4 ## Copyright (C) 2011-2012 Uwe Hermann <uwe@hermann-uwe.de>
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.
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.
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
22 # UART protocol decoder
25 import sigrokdecode as srd
28 WAIT_FOR_START_BIT = 0
34 # Used for differentiating between the two data directions.
55 # Annotation feed formats
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):
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
74 # Count number of 1 (high) bits in the data (and the parity bit itself!).
75 ones = bin(data).count('1') + parity_bit
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
83 raise Exception('Invalid parity type: %d' % parity_type)
85 class Decoder(srd.Decoder):
89 longname = 'Universal Asynchronous Receiver/Transmitter'
90 desc = 'Universal Asynchronous Receiver/Transmitter (UART)'
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'},
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).
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)'],
119 def putx(self, rxtx, data):
120 self.put(self.startsample[rxtx], self.samplenum - 1, self.out_ann, data)
122 def __init__(self, **kwargs):
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]
133 self.state = [WAIT_FOR_START_BIT, WAIT_FOR_START_BIT]
135 self.oldbit = [None, None]
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')
142 # The width of one UART bit in number of samples.
144 float(self.samplerate) / float(self.options['baudrate'])
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:
160 def reached_bit_last(self, rxtx, bitnum):
161 bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
162 if self.samplenum >= bitpos:
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):
172 # Save the sample number where the start bit begins.
173 self.frame_start[rxtx] = self.samplenum
175 self.state[rxtx] = GET_START_BIT
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):
182 self.startbit[rxtx] = signal
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?
190 self.cur_data_bit[rxtx] = 0
191 self.databyte[rxtx] = 0
192 self.startsample[rxtx] = -1
194 self.state[rxtx] = GET_DATA_BITS
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']])
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):
206 # Save the sample number where the data byte starts.
207 if self.startsample[rxtx] == -1:
208 self.startsample[rxtx] = self.samplenum
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)
219 raise Exception('Invalid bit order value: %d',
220 self.options['bit_order'])
222 # Return here, unless we already received all data bits.
224 if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
225 self.cur_data_bit[rxtx] += 1
228 self.state[rxtx] = GET_PARITY_BIT
230 self.put(self.startsample[rxtx], self.samplenum - 1, self.out_proto,
231 ['DATA', rxtx, self.databyte[rxtx]])
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:]]])
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
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):
253 self.paritybit[rxtx] = signal
255 self.state[rxtx] = GET_STOP_BITS
257 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
258 self.databyte[rxtx], self.options['num_data_bits']):
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']])
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']])
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):
280 self.stopbit1[rxtx] = signal
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?
288 self.state[rxtx] = WAIT_FOR_START_BIT
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']])
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:
300 # TODO: Start counting at 0 or 1? Increase before or after?
303 # First sample: Save RX/TX value.
304 if self.oldbit[RX] == None:
307 if self.oldbit[TX] == None:
312 for rxtx in (RX, TX):
313 signal = rx if (rxtx == RX) else tx
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)
326 raise Exception('Invalid state: %d' % self.state[rxtx])
328 # Save current RX/TX values for the next round.
329 self.oldbit[rxtx] = signal