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
21 # UART protocol decoder
23 import sigrokdecode as srd
25 # Used for differentiating between the two data directions.
29 # Annotation feed formats
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):
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
48 # Count number of 1 (high) bits in the data (and the parity bit itself!).
49 ones = bin(data).count('1') + parity_bit
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
57 raise Exception('Invalid parity type: %d' % parity_type)
59 class Decoder(srd.Decoder):
63 longname = 'Universal Asynchronous Receiver/Transmitter'
64 desc = 'Asynchronous, serial bus.'
69 # Allow specifying only one of the signals, e.g. if only one data
70 # direction exists (or is relevant).
71 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
72 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
76 'baudrate': ['Baud rate', 115200],
77 'num_data_bits': ['Data bits', 8], # Valid: 5-9.
78 'parity_type': ['Parity type', 'none'],
79 'parity_check': ['Check parity?', 'yes'], # TODO: Bool supported?
80 'num_stop_bits': ['Stop bit(s)', '1'], # String! 0, 0.5, 1, 1.5.
81 'bit_order': ['Bit order', 'lsb-first'],
82 # TODO: Options to invert the signal(s).
85 ['ASCII', 'Data bytes as ASCII characters'],
86 ['Decimal', 'Databytes as decimal, integer values'],
87 ['Hex', 'Data bytes in hex format'],
88 ['Octal', 'Data bytes as octal numbers'],
89 ['Bits', 'Data bytes in bit notation (sequence of 0/1 digits)'],
92 def putx(self, rxtx, data):
93 self.put(self.startsample[rxtx], self.samplenum - 1, self.out_ann, data)
95 def __init__(self, **kwargs):
97 self.frame_start = [-1, -1]
98 self.startbit = [-1, -1]
99 self.cur_data_bit = [0, 0]
100 self.databyte = [0, 0]
101 self.paritybit = [-1, -1]
102 self.stopbit1 = [-1, -1]
103 self.startsample = [-1, -1]
104 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
105 self.oldbit = [None, None]
107 def start(self, metadata):
108 self.samplerate = metadata['samplerate']
109 self.out_proto = self.add(srd.OUTPUT_PROTO, 'uart')
110 self.out_ann = self.add(srd.OUTPUT_ANN, 'uart')
112 # The width of one UART bit in number of samples.
114 float(self.samplerate) / float(self.options['baudrate'])
119 # Return true if we reached the middle of the desired bit, false otherwise.
120 def reached_bit(self, rxtx, bitnum):
121 # bitpos is the samplenumber which is in the middle of the
122 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
123 # (if used) or the first stop bit, and so on).
124 bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
125 bitpos += bitnum * self.bit_width
126 if self.samplenum >= bitpos:
130 def reached_bit_last(self, rxtx, bitnum):
131 bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
132 if self.samplenum >= bitpos:
136 def wait_for_start_bit(self, rxtx, old_signal, signal):
137 # The start bit is always 0 (low). As the idle UART (and the stop bit)
138 # level is 1 (high), the beginning of a start bit is a falling edge.
139 if not (old_signal == 1 and signal == 0):
142 # Save the sample number where the start bit begins.
143 self.frame_start[rxtx] = self.samplenum
145 self.state[rxtx] = 'GET START BIT'
147 def get_start_bit(self, rxtx, signal):
148 # Skip samples until we're in the middle of the start bit.
149 if not self.reached_bit(rxtx, 0):
152 self.startbit[rxtx] = signal
154 # The startbit must be 0. If not, we report an error.
155 if self.startbit[rxtx] != 0:
156 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
157 ['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
158 # TODO: Abort? Ignore rest of the frame?
160 self.cur_data_bit[rxtx] = 0
161 self.databyte[rxtx] = 0
162 self.startsample[rxtx] = -1
164 self.state[rxtx] = 'GET DATA BITS'
166 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
167 ['STARTBIT', rxtx, self.startbit[rxtx]])
168 self.put(self.frame_start[rxtx], self.samplenum, self.out_ann,
169 [ANN_ASCII, ['Start bit', 'Start', 'S']])
171 def get_data_bits(self, rxtx, signal):
172 # Skip samples until we're in the middle of the desired data bit.
173 if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
176 # Save the sample number where the data byte starts.
177 if self.startsample[rxtx] == -1:
178 self.startsample[rxtx] = self.samplenum
180 # Get the next data bit in LSB-first or MSB-first fashion.
181 if self.options['bit_order'] == 'lsb-first':
182 self.databyte[rxtx] >>= 1
183 self.databyte[rxtx] |= \
184 (signal << (self.options['num_data_bits'] - 1))
185 elif self.options['bit_order'] == 'msb-first':
186 self.databyte[rxtx] <<= 1
187 self.databyte[rxtx] |= (signal << 0)
189 raise Exception('Invalid bit order value: %s',
190 self.options['bit_order'])
192 # Return here, unless we already received all data bits.
194 if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
195 self.cur_data_bit[rxtx] += 1
198 self.state[rxtx] = 'GET PARITY BIT'
200 self.put(self.startsample[rxtx], self.samplenum - 1, self.out_proto,
201 ['DATA', rxtx, self.databyte[rxtx]])
203 s = 'RX: ' if (rxtx == RX) else 'TX: '
204 self.putx(rxtx, [ANN_ASCII, [s + chr(self.databyte[rxtx])]])
205 self.putx(rxtx, [ANN_DEC, [s + str(self.databyte[rxtx])]])
206 self.putx(rxtx, [ANN_HEX, [s + hex(self.databyte[rxtx]),
207 s + hex(self.databyte[rxtx])[2:]]])
208 self.putx(rxtx, [ANN_OCT, [s + oct(self.databyte[rxtx]),
209 s + oct(self.databyte[rxtx])[2:]]])
210 self.putx(rxtx, [ANN_BITS, [s + bin(self.databyte[rxtx]),
211 s + bin(self.databyte[rxtx])[2:]]])
213 def get_parity_bit(self, rxtx, signal):
214 # If no parity is used/configured, skip to the next state immediately.
215 if self.options['parity_type'] == 'none':
216 self.state[rxtx] = 'GET STOP BITS'
219 # Skip samples until we're in the middle of the parity bit.
220 if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
223 self.paritybit[rxtx] = signal
225 self.state[rxtx] = 'GET STOP BITS'
227 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
228 self.databyte[rxtx], self.options['num_data_bits']):
230 self.put(self.samplenum, self.samplenum, self.out_proto,
231 ['PARITYBIT', rxtx, self.paritybit[rxtx]])
232 self.put(self.samplenum, self.samplenum, self.out_ann,
233 [ANN_ASCII, ['Parity bit', 'Parity', 'P']])
236 # TODO: Return expected/actual parity values.
237 self.put(self.samplenum, self.samplenum, self.out_proto,
238 ['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
239 self.put(self.samplenum, self.samplenum, self.out_ann,
240 [ANN_ASCII, ['Parity error', 'Parity err', 'PE']])
242 # TODO: Currently only supports 1 stop bit.
243 def get_stop_bits(self, rxtx, signal):
244 # Skip samples until we're in the middle of the stop bit(s).
245 skip_parity = 0 if self.options['parity_type'] == 'none' else 1
246 b = self.options['num_data_bits'] + 1 + skip_parity
247 if not self.reached_bit(rxtx, b):
250 self.stopbit1[rxtx] = signal
252 # Stop bits must be 1. If not, we report an error.
253 if self.stopbit1[rxtx] != 1:
254 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
255 ['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
256 # TODO: Abort? Ignore the frame? Other?
258 self.state[rxtx] = 'WAIT FOR START BIT'
261 self.put(self.samplenum, self.samplenum, self.out_proto,
262 ['STOPBIT', rxtx, self.stopbit1[rxtx]])
263 self.put(self.samplenum, self.samplenum, self.out_ann,
264 [ANN_ASCII, ['Stop bit', 'Stop', 'P']])
266 def decode(self, ss, es, data):
267 # TODO: Either RX or TX could be omitted (optional probe).
268 for (self.samplenum, (rx, tx)) in data:
270 # First sample: Save RX/TX value.
271 if self.oldbit[RX] == None:
274 if self.oldbit[TX] == None:
279 for rxtx in (RX, TX):
280 signal = rx if (rxtx == RX) else tx
282 if self.state[rxtx] == 'WAIT FOR START BIT':
283 self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
284 elif self.state[rxtx] == 'GET START BIT':
285 self.get_start_bit(rxtx, signal)
286 elif self.state[rxtx] == 'GET DATA BITS':
287 self.get_data_bits(rxtx, signal)
288 elif self.state[rxtx] == 'GET PARITY BIT':
289 self.get_parity_bit(rxtx, signal)
290 elif self.state[rxtx] == 'GET STOP BITS':
291 self.get_stop_bits(rxtx, signal)
293 raise Exception('Invalid state: %d' % self.state[rxtx])
295 # Save current RX/TX values for the next round.
296 self.oldbit[rxtx] = signal