2 ## This file is part of the libsigrokdecode project.
4 ## Copyright (C) 2011-2014 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 import sigrokdecode as srd
22 from math import floor, ceil
28 [<ptype>, <rxtx>, <pdata>]
30 This is the list of <ptype>s and their respective <pdata> values:
31 - 'STARTBIT': The data is the (integer) value of the start bit (0/1).
32 - 'DATA': This is always a tuple containing two items:
33 - 1st item: 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 - 2nd item: the list of individual data bits and their ss/es numbers.
36 - 'PARITYBIT': The data is the (integer) value of the parity bit (0/1).
37 - 'STOPBIT': The data is the (integer) value of the stop bit (0 or 1).
38 - 'INVALID STARTBIT': The data is the (integer) value of the start bit (0/1).
39 - 'INVALID STOPBIT': The data is the (integer) value of the stop bit (0/1).
40 - 'PARITY ERROR': The data is a tuple with two entries. The first one is
41 the expected parity value, the second is the actual parity value.
44 The <rxtx> field is 0 for RX packets, 1 for TX packets.
47 # Used for differentiating between the two data directions.
51 # Given a parity type to check (odd, even, zero, one), the value of the
52 # parity bit, the value of the data, and the length of the data (5-9 bits,
53 # usually 8 bits) return True if the parity is correct, False otherwise.
54 # 'none' is _not_ allowed as value for 'parity_type'.
55 def parity_ok(parity_type, parity_bit, data, num_data_bits):
57 # Handle easy cases first (parity bit is always 1 or 0).
58 if parity_type == 'zero':
59 return parity_bit == 0
60 elif parity_type == 'one':
61 return parity_bit == 1
63 # Count number of 1 (high) bits in the data (and the parity bit itself!).
64 ones = bin(data).count('1') + parity_bit
66 # Check for odd/even parity.
67 if parity_type == 'odd':
68 return (ones % 2) == 1
69 elif parity_type == 'even':
70 return (ones % 2) == 0
72 class SamplerateError(Exception):
75 class ChannelError(Exception):
78 class Decoder(srd.Decoder):
82 longname = 'Universal Asynchronous Receiver/Transmitter'
83 desc = 'Asynchronous, serial bus.'
88 # Allow specifying only one of the signals, e.g. if only one data
89 # direction exists (or is relevant).
90 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
91 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
94 {'id': 'baudrate', 'desc': 'Baud rate', 'default': 115200},
95 {'id': 'num_data_bits', 'desc': 'Data bits', 'default': 8,
96 'values': (5, 6, 7, 8, 9)},
97 {'id': 'parity_type', 'desc': 'Parity type', 'default': 'none',
98 'values': ('none', 'odd', 'even', 'zero', 'one')},
99 {'id': 'parity_check', 'desc': 'Check parity?', 'default': 'yes',
100 'values': ('yes', 'no')},
101 {'id': 'num_stop_bits', 'desc': 'Stop bits', 'default': 1.0,
102 'values': (0.0, 0.5, 1.0, 1.5)},
103 {'id': 'bit_order', 'desc': 'Bit order', 'default': 'lsb-first',
104 'values': ('lsb-first', 'msb-first')},
105 {'id': 'format', 'desc': 'Data format', 'default': 'ascii',
106 'values': ('ascii', 'dec', 'hex', 'oct', 'bin')},
107 {'id': 'invert_rx', 'desc': 'Invert RX?', 'default': 'no',
108 'values': ('yes', 'no')},
109 {'id': 'invert_tx', 'desc': 'Invert TX?', 'default': 'no',
110 'values': ('yes', 'no')},
113 ('rx-data', 'RX data'),
114 ('tx-data', 'TX data'),
115 ('rx-start', 'RX start bits'),
116 ('tx-start', 'TX start bits'),
117 ('rx-parity-ok', 'RX parity OK bits'),
118 ('tx-parity-ok', 'TX parity OK bits'),
119 ('rx-parity-err', 'RX parity error bits'),
120 ('tx-parity-err', 'TX parity error bits'),
121 ('rx-stop', 'RX stop bits'),
122 ('tx-stop', 'TX stop bits'),
123 ('rx-warnings', 'RX warnings'),
124 ('tx-warnings', 'TX warnings'),
125 ('rx-data-bits', 'RX data bits'),
126 ('tx-data-bits', 'TX data bits'),
129 ('rx-data', 'RX', (0, 2, 4, 6, 8)),
130 ('rx-data-bits', 'RX bits', (12,)),
131 ('rx-warnings', 'RX warnings', (10,)),
132 ('tx-data', 'TX', (1, 3, 5, 7, 9)),
133 ('tx-data-bits', 'TX bits', (13,)),
134 ('tx-warnings', 'TX warnings', (11,)),
139 ('rxtx', 'RX/TX dump'),
142 def putx(self, rxtx, data):
143 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
144 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
146 def putpx(self, rxtx, data):
147 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
148 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_python, data)
150 def putg(self, data):
151 s, halfbit = self.samplenum, self.bit_width / 2.0
152 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data)
154 def putp(self, data):
155 s, halfbit = self.samplenum, self.bit_width / 2.0
156 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_python, data)
158 def putbin(self, rxtx, data):
159 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
160 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_bin, data)
162 def __init__(self, **kwargs):
163 self.samplerate = None
165 self.frame_start = [-1, -1]
166 self.startbit = [-1, -1]
167 self.cur_data_bit = [0, 0]
168 self.databyte = [0, 0]
169 self.paritybit = [-1, -1]
170 self.stopbit1 = [-1, -1]
171 self.startsample = [-1, -1]
172 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
174 self.oldpins = [1, 1]
175 self.databits = [[], []]
178 self.out_python = self.register(srd.OUTPUT_PYTHON)
179 self.out_bin = self.register(srd.OUTPUT_BINARY)
180 self.out_ann = self.register(srd.OUTPUT_ANN)
182 def metadata(self, key, value):
183 if key == srd.SRD_CONF_SAMPLERATE:
184 self.samplerate = value
185 # The width of one UART bit in number of samples.
186 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
188 # Return true if we reached the middle of the desired bit, false otherwise.
189 def reached_bit(self, rxtx, bitnum):
190 # bitpos is the samplenumber which is in the middle of the
191 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
192 # (if used) or the first stop bit, and so on).
193 # The samples within bit are 0, 1, ..., (bit_width - 1), therefore
194 # index of the middle sample within bit window is (bit_width - 1) / 2.
195 bitpos = self.frame_start[rxtx] + (self.bit_width - 1) / 2.0
196 bitpos += bitnum * self.bit_width
197 if self.samplenum >= bitpos:
201 def reached_bit_last(self, rxtx, bitnum):
202 bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
203 if self.samplenum >= bitpos:
207 def wait_for_start_bit(self, rxtx, old_signal, signal):
208 # The start bit is always 0 (low). As the idle UART (and the stop bit)
209 # level is 1 (high), the beginning of a start bit is a falling edge.
210 if not (old_signal == 1 and signal == 0):
213 # Save the sample number where the start bit begins.
214 self.frame_start[rxtx] = self.samplenum
216 self.state[rxtx] = 'GET START BIT'
218 def get_start_bit(self, rxtx, signal):
219 # Skip samples until we're in the middle of the start bit.
220 if not self.reached_bit(rxtx, 0):
223 self.startbit[rxtx] = signal
225 # The startbit must be 0. If not, we report an error.
226 if self.startbit[rxtx] != 0:
227 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
228 # TODO: Abort? Ignore rest of the frame?
230 self.cur_data_bit[rxtx] = 0
231 self.databyte[rxtx] = 0
232 self.startsample[rxtx] = -1
234 self.state[rxtx] = 'GET DATA BITS'
236 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
237 self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
239 def get_data_bits(self, rxtx, signal):
240 # Skip samples until we're in the middle of the desired data bit.
241 if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
244 # Save the sample number of the middle of the first data bit.
245 if self.startsample[rxtx] == -1:
246 self.startsample[rxtx] = self.samplenum
248 # Get the next data bit in LSB-first or MSB-first fashion.
249 if self.options['bit_order'] == 'lsb-first':
250 self.databyte[rxtx] >>= 1
251 self.databyte[rxtx] |= \
252 (signal << (self.options['num_data_bits'] - 1))
254 self.databyte[rxtx] <<= 1
255 self.databyte[rxtx] |= (signal << 0)
257 self.putg([rxtx + 12, ['%d' % signal]])
259 # Store individual data bits and their start/end samplenumbers.
260 s, halfbit = self.samplenum, int(self.bit_width / 2)
261 self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
263 # Return here, unless we already received all data bits.
264 if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
265 self.cur_data_bit[rxtx] += 1
268 self.state[rxtx] = 'GET PARITY BIT'
270 self.putpx(rxtx, ['DATA', rxtx,
271 (self.databyte[rxtx], self.databits[rxtx])])
273 b, f = self.databyte[rxtx], self.options['format']
275 c = chr(b) if b in range(30, 126 + 1) else '[%02X]' % b
276 self.putx(rxtx, [rxtx, [c]])
278 self.putx(rxtx, [rxtx, [str(b)]])
280 self.putx(rxtx, [rxtx, [hex(b)[2:].zfill(2).upper()]])
282 self.putx(rxtx, [rxtx, [oct(b)[2:].zfill(3)]])
284 self.putx(rxtx, [rxtx, [bin(b)[2:].zfill(8)]])
286 self.putbin(rxtx, (rxtx, bytes([b])))
287 self.putbin(rxtx, (2, bytes([b])))
289 self.databits = [[], []]
291 def get_parity_bit(self, rxtx, signal):
292 # If no parity is used/configured, skip to the next state immediately.
293 if self.options['parity_type'] == 'none':
294 self.state[rxtx] = 'GET STOP BITS'
297 # Skip samples until we're in the middle of the parity bit.
298 if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
301 self.paritybit[rxtx] = signal
303 self.state[rxtx] = 'GET STOP BITS'
305 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
306 self.databyte[rxtx], self.options['num_data_bits']):
307 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
308 self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
310 # TODO: Return expected/actual parity values.
311 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
312 self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
314 # TODO: Currently only supports 1 stop bit.
315 def get_stop_bits(self, rxtx, signal):
316 # Skip samples until we're in the middle of the stop bit(s).
317 skip_parity = 0 if self.options['parity_type'] == 'none' else 1
318 b = self.options['num_data_bits'] + 1 + skip_parity
319 if not self.reached_bit(rxtx, b):
322 self.stopbit1[rxtx] = signal
324 # Stop bits must be 1. If not, we report an error.
325 if self.stopbit1[rxtx] != 1:
326 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
327 self.putg([rxtx + 8, ['Frame error', 'Frame err', 'FE']])
328 # TODO: Abort? Ignore the frame? Other?
330 self.state[rxtx] = 'WAIT FOR START BIT'
332 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
333 self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
335 def decode(self, ss, es, data):
336 if not self.samplerate:
337 raise SamplerateError('Cannot decode without samplerate.')
338 for (self.samplenum, pins) in data:
340 # Note: Ignoring identical samples here for performance reasons
341 # is not possible for this PD, at least not in the current state.
342 # if self.oldpins == pins:
344 self.oldpins, (rx, tx) = pins, pins
346 if self.options['invert_rx'] == 'yes':
348 if self.options['invert_tx'] == 'yes':
351 # Either RX or TX (but not both) can be omitted.
352 has_pin = [rx in (0, 1), tx in (0, 1)]
353 if has_pin == [False, False]:
354 raise ChannelError('Either TX or RX (or both) pins required.')
357 for rxtx in (RX, TX):
358 # Don't try to handle RX (or TX) if not supplied.
359 if not has_pin[rxtx]:
362 signal = rx if (rxtx == RX) else tx
364 if self.state[rxtx] == 'WAIT FOR START BIT':
365 self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
366 elif self.state[rxtx] == 'GET START BIT':
367 self.get_start_bit(rxtx, signal)
368 elif self.state[rxtx] == 'GET DATA BITS':
369 self.get_data_bits(rxtx, signal)
370 elif self.state[rxtx] == 'GET PARITY BIT':
371 self.get_parity_bit(rxtx, signal)
372 elif self.state[rxtx] == 'GET STOP BITS':
373 self.get_stop_bits(rxtx, signal)
375 # Save current RX/TX values for the next round.
376 self.oldbit[rxtx] = signal