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, see <http://www.gnu.org/licenses/>.
20 import sigrokdecode as srd
21 from common.srdhelper import bitpack
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 511 (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': 'hex',
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'),
141 idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
143 def putx(self, rxtx, data):
144 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
145 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
147 def putpx(self, rxtx, data):
148 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
149 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_python, data)
151 def putg(self, data):
152 s, halfbit = self.samplenum, self.bit_width / 2.0
153 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data)
155 def putp(self, data):
156 s, halfbit = self.samplenum, self.bit_width / 2.0
157 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_python, data)
159 def putbin(self, rxtx, data):
160 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
161 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_binary, data)
167 self.samplerate = None
169 self.frame_start = [-1, -1]
170 self.startbit = [-1, -1]
171 self.cur_data_bit = [0, 0]
172 self.datavalue = [0, 0]
173 self.paritybit = [-1, -1]
174 self.stopbit1 = [-1, -1]
175 self.startsample = [-1, -1]
176 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
177 self.databits = [[], []]
180 self.out_python = self.register(srd.OUTPUT_PYTHON)
181 self.out_binary = self.register(srd.OUTPUT_BINARY)
182 self.out_ann = self.register(srd.OUTPUT_ANN)
183 self.bw = (self.options['num_data_bits'] + 7) // 8
185 def metadata(self, key, value):
186 if key == srd.SRD_CONF_SAMPLERATE:
187 self.samplerate = value
188 # The width of one UART bit in number of samples.
189 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
191 def get_sample_point(self, rxtx, bitnum):
192 # Determine absolute sample number of a bit slot's sample point.
193 # bitpos is the samplenumber which is in the middle of the
194 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
195 # (if used) or the first stop bit, and so on).
196 # The samples within bit are 0, 1, ..., (bit_width - 1), therefore
197 # index of the middle sample within bit window is (bit_width - 1) / 2.
198 bitpos = self.frame_start[rxtx] + (self.bit_width - 1) / 2.0
199 bitpos += bitnum * self.bit_width
202 def wait_for_start_bit(self, rxtx, signal):
203 # Save the sample number where the start bit begins.
204 self.frame_start[rxtx] = self.samplenum
206 self.state[rxtx] = 'GET START BIT'
208 def get_start_bit(self, rxtx, signal):
209 self.startbit[rxtx] = signal
211 # The startbit must be 0. If not, we report an error and wait
212 # for the next start bit (assuming this one was spurious).
213 if self.startbit[rxtx] != 0:
214 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
215 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
216 self.state[rxtx] = 'WAIT FOR START BIT'
219 self.cur_data_bit[rxtx] = 0
220 self.datavalue[rxtx] = 0
221 self.startsample[rxtx] = -1
223 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
224 self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
226 self.state[rxtx] = 'GET DATA BITS'
228 def get_data_bits(self, rxtx, signal):
229 # Save the sample number of the middle of the first data bit.
230 if self.startsample[rxtx] == -1:
231 self.startsample[rxtx] = self.samplenum
233 self.putg([rxtx + 12, ['%d' % signal]])
235 # Store individual data bits and their start/end samplenumbers.
236 s, halfbit = self.samplenum, int(self.bit_width / 2)
237 self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
239 # Return here, unless we already received all data bits.
240 self.cur_data_bit[rxtx] += 1
241 if self.cur_data_bit[rxtx] < self.options['num_data_bits']:
244 # Convert accumulated data bits to a data value.
245 bits = [b[0] for b in self.databits[rxtx]]
246 if self.options['bit_order'] == 'msb-first':
248 self.datavalue[rxtx] = bitpack(bits)
249 self.putpx(rxtx, ['DATA', rxtx,
250 (self.datavalue[rxtx], self.databits[rxtx])])
252 b = self.datavalue[rxtx]
253 formatted = self.format_value(b)
254 if formatted is not None:
255 self.putx(rxtx, [rxtx, [formatted]])
257 bdata = b.to_bytes(self.bw, byteorder='big')
258 self.putbin(rxtx, [rxtx, bdata])
259 self.putbin(rxtx, [2, bdata])
261 self.databits[rxtx] = []
263 # Advance to either reception of the parity bit, or reception of
264 # the STOP bits if parity is not applicable.
265 self.state[rxtx] = 'GET PARITY BIT'
266 if self.options['parity_type'] == 'none':
267 self.state[rxtx] = 'GET STOP BITS'
269 def format_value(self, v):
270 # Format value 'v' according to configured options.
271 # Reflects the user selected kind of representation, as well as
272 # the number of data bits in the UART frames.
274 fmt, bits = self.options['format'], self.options['num_data_bits']
276 # Assume "is printable" for values from 32 to including 126,
277 # below 32 is "control" and thus not printable, above 127 is
278 # "not ASCII" in its strict sense, 127 (DEL) is not printable,
279 # fall back to hex representation for non-printables.
281 if v in range(32, 126 + 1):
283 hexfmt = "[{:02X}]" if bits <= 8 else "[{:03X}]"
284 return hexfmt.format(v)
286 # Mere number to text conversion without prefix and padding
287 # for the "decimal" output format.
289 return "{:d}".format(v)
291 # Padding with leading zeroes for hex/oct/bin formats, but
292 # without a prefix for density -- since the format is user
293 # specified, there is no ambiguity.
295 digits = (bits + 4 - 1) // 4
298 digits = (bits + 3 - 1) // 3
305 if fmtchar is not None:
306 fmt = "{{:0{:d}{:s}}}".format(digits, fmtchar)
311 def get_parity_bit(self, rxtx, signal):
312 self.paritybit[rxtx] = signal
314 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
315 self.datavalue[rxtx], self.options['num_data_bits']):
316 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
317 self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
319 # TODO: Return expected/actual parity values.
320 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
321 self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
323 self.state[rxtx] = 'GET STOP BITS'
325 # TODO: Currently only supports 1 stop bit.
326 def get_stop_bits(self, rxtx, signal):
327 self.stopbit1[rxtx] = signal
329 # Stop bits must be 1. If not, we report an error.
330 if self.stopbit1[rxtx] != 1:
331 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
332 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
333 # TODO: Abort? Ignore the frame? Other?
335 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
336 self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
338 self.state[rxtx] = 'WAIT FOR START BIT'
340 def get_wait_cond(self, rxtx, inv):
341 # Return condititions that are suitable for Decoder.wait(). Those
342 # conditions either match the falling edge of the START bit, or
343 # the sample point of the next bit time.
344 state = self.state[rxtx]
345 if state == 'WAIT FOR START BIT':
346 return {rxtx: 'r' if inv else 'f'}
347 if state == 'GET START BIT':
349 elif state == 'GET DATA BITS':
350 bitnum = 1 + self.cur_data_bit[rxtx]
351 elif state == 'GET PARITY BIT':
352 bitnum = 1 + self.options['num_data_bits']
353 elif state == 'GET STOP BITS':
354 bitnum = 1 + self.options['num_data_bits']
355 bitnum += 0 if self.options['parity_type'] == 'none' else 1
356 want_num = ceil(self.get_sample_point(rxtx, bitnum))
357 return {'skip': want_num - self.samplenum}
359 def inspect_sample(self, rxtx, signal, inv):
360 # Inspect a sample returned by .wait() for the specified UART line.
364 state = self.state[rxtx]
365 if state == 'WAIT FOR START BIT':
366 self.wait_for_start_bit(rxtx, signal)
367 elif state == 'GET START BIT':
368 self.get_start_bit(rxtx, signal)
369 elif state == 'GET DATA BITS':
370 self.get_data_bits(rxtx, signal)
371 elif state == 'GET PARITY BIT':
372 self.get_parity_bit(rxtx, signal)
373 elif state == 'GET STOP BITS':
374 self.get_stop_bits(rxtx, signal)
377 if not self.samplerate:
378 raise SamplerateError('Cannot decode without samplerate.')
380 has_pin = [self.has_channel(ch) for ch in (RX, TX)]
381 if has_pin == [False, False]:
382 raise ChannelError('Either TX or RX (or both) pins required.')
385 inv = [opt['invert_rx'] == 'yes', opt['invert_tx'] == 'yes']
386 cond_idx = [None] * len(has_pin)
391 cond_idx[RX] = len(conds)
392 conds.append(self.get_wait_cond(RX, inv[RX]))
394 cond_idx[TX] = len(conds)
395 conds.append(self.get_wait_cond(TX, inv[TX]))
396 (rx, tx) = self.wait(conds)
397 if cond_idx[RX] is not None and self.matched[cond_idx[RX]]:
398 self.inspect_sample(RX, rx, inv[RX])
399 if cond_idx[TX] is not None and self.matched[cond_idx[TX]]:
400 self.inspect_sample(TX, tx, inv[TX])