2 ## This file is part of the libsigrokdecode project.
4 ## Copyright (C) 2011-2013 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
26 Protocol output format:
29 [<packet-type>, <rxtx>, <packet-data>]
31 This is the list of <packet-type>s and their respective <packet-data>:
32 - 'STARTBIT': The data is the (integer) value of the start bit (0/1).
33 - 'DATA': The data is the (integer) value of the UART data. Valid values
34 range from 0 to 512 (as the data can be up to 9 bits in size).
35 - 'PARITYBIT': The data is the (integer) value of the parity bit (0/1).
36 - 'STOPBIT': The data is the (integer) value of the stop bit (0 or 1).
37 - 'INVALID STARTBIT': The data is the (integer) value of the start bit (0/1).
38 - 'INVALID STOPBIT': The data is the (integer) value of the stop bit (0/1).
39 - 'PARITY ERROR': The data is a tuple with two entries. The first one is
40 the expected parity value, the second is the actual parity value.
43 The <rxtx> field is 0 for RX packets, 1 for TX packets.
46 # Used for differentiating between the two data directions.
50 # Given a parity type to check (odd, even, zero, one), the value of the
51 # parity bit, the value of the data, and the length of the data (5-9 bits,
52 # usually 8 bits) return True if the parity is correct, False otherwise.
53 # 'none' is _not_ allowed as value for 'parity_type'.
54 def parity_ok(parity_type, parity_bit, data, num_data_bits):
56 # Handle easy cases first (parity bit is always 1 or 0).
57 if parity_type == 'zero':
58 return parity_bit == 0
59 elif parity_type == 'one':
60 return parity_bit == 1
62 # Count number of 1 (high) bits in the data (and the parity bit itself!).
63 ones = bin(data).count('1') + parity_bit
65 # Check for odd/even parity.
66 if parity_type == 'odd':
67 return (ones % 2) == 1
68 elif parity_type == 'even':
69 return (ones % 2) == 0
71 raise Exception('Invalid parity type: %d' % parity_type)
73 class Decoder(srd.Decoder):
77 longname = 'Universal Asynchronous Receiver/Transmitter'
78 desc = 'Asynchronous, serial bus.'
83 # Allow specifying only one of the signals, e.g. if only one data
84 # direction exists (or is relevant).
85 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
86 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
90 'baudrate': ['Baud rate', 115200],
91 'num_data_bits': ['Data bits', 8], # Valid: 5-9.
92 'parity_type': ['Parity type', 'none'],
93 'parity_check': ['Check parity?', 'yes'], # TODO: Bool supported?
94 'num_stop_bits': ['Stop bit(s)', '1'], # String! 0, 0.5, 1, 1.5.
95 'bit_order': ['Bit order', 'lsb-first'],
96 'format': ['Data format', 'ascii'], # ascii/dec/hex/oct/bin
97 # TODO: Options to invert the signal(s).
100 ['RX data', 'UART RX data'],
101 ['TX data', 'UART TX data'],
102 ['Start bits', 'UART start bits'],
103 ['Parity bits', 'UART parity bits'],
104 ['Stop bits', 'UART stop bits'],
105 ['Warnings', 'Warnings'],
108 def putx(self, rxtx, data):
109 s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
110 self.put(s - halfbit, self.samplenum + halfbit, self.out_ann, data)
112 def putg(self, data):
113 s, halfbit = self.samplenum, int(self.bit_width / 2)
114 self.put(s - halfbit, s + halfbit, self.out_ann, data)
116 def putp(self, data):
117 s, halfbit = self.samplenum, int(self.bit_width / 2)
118 self.put(s - halfbit, s + halfbit, self.out_proto, data)
120 def __init__(self, **kwargs):
121 self.samplerate = None
123 self.frame_start = [-1, -1]
124 self.startbit = [-1, -1]
125 self.cur_data_bit = [0, 0]
126 self.databyte = [0, 0]
127 self.paritybit = [-1, -1]
128 self.stopbit1 = [-1, -1]
129 self.startsample = [-1, -1]
130 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
132 self.oldpins = [1, 1]
135 self.out_proto = self.register(srd.OUTPUT_PYTHON)
136 self.out_ann = self.register(srd.OUTPUT_ANN)
138 def metadata(self, key, value):
139 if key == srd.SRD_CONF_SAMPLERATE:
140 self.samplerate = value;
141 # The width of one UART bit in number of samples.
142 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
144 # Return true if we reached the middle of the desired bit, false otherwise.
145 def reached_bit(self, rxtx, bitnum):
146 # bitpos is the samplenumber which is in the middle of the
147 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
148 # (if used) or the first stop bit, and so on).
149 bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
150 bitpos += bitnum * self.bit_width
151 if self.samplenum >= bitpos:
155 def reached_bit_last(self, rxtx, bitnum):
156 bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
157 if self.samplenum >= bitpos:
161 def wait_for_start_bit(self, rxtx, old_signal, signal):
162 # The start bit is always 0 (low). As the idle UART (and the stop bit)
163 # level is 1 (high), the beginning of a start bit is a falling edge.
164 if not (old_signal == 1 and signal == 0):
167 # Save the sample number where the start bit begins.
168 self.frame_start[rxtx] = self.samplenum
170 self.state[rxtx] = 'GET START BIT'
172 def get_start_bit(self, rxtx, signal):
173 # Skip samples until we're in the middle of the start bit.
174 if not self.reached_bit(rxtx, 0):
177 self.startbit[rxtx] = signal
179 # The startbit must be 0. If not, we report an error.
180 if self.startbit[rxtx] != 0:
181 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
182 # TODO: Abort? Ignore rest of the frame?
184 self.cur_data_bit[rxtx] = 0
185 self.databyte[rxtx] = 0
186 self.startsample[rxtx] = -1
188 self.state[rxtx] = 'GET DATA BITS'
190 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
191 self.putg([2, ['Start bit', 'Start', 'S']])
193 def get_data_bits(self, rxtx, signal):
194 # Skip samples until we're in the middle of the desired data bit.
195 if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
198 # Save the sample number of the middle of the first data bit.
199 if self.startsample[rxtx] == -1:
200 self.startsample[rxtx] = self.samplenum
202 # Get the next data bit in LSB-first or MSB-first fashion.
203 if self.options['bit_order'] == 'lsb-first':
204 self.databyte[rxtx] >>= 1
205 self.databyte[rxtx] |= \
206 (signal << (self.options['num_data_bits'] - 1))
207 elif self.options['bit_order'] == 'msb-first':
208 self.databyte[rxtx] <<= 1
209 self.databyte[rxtx] |= (signal << 0)
211 raise Exception('Invalid bit order value: %s',
212 self.options['bit_order'])
214 # Return here, unless we already received all data bits.
215 if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
216 self.cur_data_bit[rxtx] += 1
219 self.state[rxtx] = 'GET PARITY BIT'
221 self.putp(['DATA', rxtx, self.databyte[rxtx]])
223 b, f = self.databyte[rxtx], self.options['format']
225 c = chr(b) if chr(b).isprintable() else '[%02X]' % b
226 self.putx(rxtx, [rxtx, [c]])
228 self.putx(rxtx, [rxtx, [str(b)]])
230 self.putx(rxtx, [rxtx, [hex(b)[2:].zfill(2).upper()]])
232 self.putx(rxtx, [rxtx, [oct(b)[2:].zfill(3)]])
234 self.putx(rxtx, [rxtx, [bin(b)[2:].zfill(8)]])
236 raise Exception('Invalid data format option: %s' % f)
238 def get_parity_bit(self, rxtx, signal):
239 # If no parity is used/configured, skip to the next state immediately.
240 if self.options['parity_type'] == 'none':
241 self.state[rxtx] = 'GET STOP BITS'
244 # Skip samples until we're in the middle of the parity bit.
245 if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
248 self.paritybit[rxtx] = signal
250 self.state[rxtx] = 'GET STOP BITS'
252 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
253 self.databyte[rxtx], self.options['num_data_bits']):
254 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
255 self.putg([3, ['Parity bit', 'Parity', 'P']])
257 # TODO: Return expected/actual parity values.
258 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
259 self.putg([5, ['Parity error', 'Parity err', 'PE']])
261 # TODO: Currently only supports 1 stop bit.
262 def get_stop_bits(self, rxtx, signal):
263 # Skip samples until we're in the middle of the stop bit(s).
264 skip_parity = 0 if self.options['parity_type'] == 'none' else 1
265 b = self.options['num_data_bits'] + 1 + skip_parity
266 if not self.reached_bit(rxtx, b):
269 self.stopbit1[rxtx] = signal
271 # Stop bits must be 1. If not, we report an error.
272 if self.stopbit1[rxtx] != 1:
273 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
274 self.putg([5, ['Frame error', 'Frame err', 'FE']])
275 # TODO: Abort? Ignore the frame? Other?
277 self.state[rxtx] = 'WAIT FOR START BIT'
279 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
280 self.putg([4, ['Stop bit', 'Stop', 'T']])
282 def decode(self, ss, es, data):
283 if self.samplerate is None:
284 raise Exception("Cannot decode without samplerate.")
285 # TODO: Either RX or TX could be omitted (optional probe).
286 for (self.samplenum, pins) in data:
288 # Note: Ignoring identical samples here for performance reasons
289 # is not possible for this PD, at least not in the current state.
290 # if self.oldpins == pins:
292 self.oldpins, (rx, tx) = pins, pins
295 for rxtx in (RX, TX):
296 signal = rx if (rxtx == RX) else tx
298 if self.state[rxtx] == 'WAIT FOR START BIT':
299 self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
300 elif self.state[rxtx] == 'GET START BIT':
301 self.get_start_bit(rxtx, signal)
302 elif self.state[rxtx] == 'GET DATA BITS':
303 self.get_data_bits(rxtx, signal)
304 elif self.state[rxtx] == 'GET PARITY BIT':
305 self.get_parity_bit(rxtx, signal)
306 elif self.state[rxtx] == 'GET STOP BITS':
307 self.get_stop_bits(rxtx, signal)
309 raise Exception('Invalid state: %s' % self.state[rxtx])
311 # Save current RX/TX values for the next round.
312 self.oldbit[rxtx] = signal