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.
42 - 'BREAK': The data is always 0.
43 - 'FRAME': The data is always a tuple containing two items: The (integer)
44 value of the UART data, and a boolean which reflects the validity of the
47 The <rxtx> field is 0 for RX packets, 1 for TX packets.
50 # Used for differentiating between the two data directions.
54 # Given a parity type to check (odd, even, zero, one), the value of the
55 # parity bit, the value of the data, and the length of the data (5-9 bits,
56 # usually 8 bits) return True if the parity is correct, False otherwise.
57 # 'none' is _not_ allowed as value for 'parity_type'.
58 def parity_ok(parity_type, parity_bit, data, num_data_bits):
60 # Handle easy cases first (parity bit is always 1 or 0).
61 if parity_type == 'zero':
62 return parity_bit == 0
63 elif parity_type == 'one':
64 return parity_bit == 1
66 # Count number of 1 (high) bits in the data (and the parity bit itself!).
67 ones = bin(data).count('1') + parity_bit
69 # Check for odd/even parity.
70 if parity_type == 'odd':
71 return (ones % 2) == 1
72 elif parity_type == 'even':
73 return (ones % 2) == 0
75 class SamplerateError(Exception):
78 class ChannelError(Exception):
81 class Decoder(srd.Decoder):
85 longname = 'Universal Asynchronous Receiver/Transmitter'
86 desc = 'Asynchronous, serial bus.'
90 tags = ['Embedded/industrial']
92 # Allow specifying only one of the signals, e.g. if only one data
93 # direction exists (or is relevant).
94 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
95 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
98 {'id': 'baudrate', 'desc': 'Baud rate', 'default': 115200},
99 {'id': 'num_data_bits', 'desc': 'Data bits', 'default': 8,
100 'values': (5, 6, 7, 8, 9)},
101 {'id': 'parity_type', 'desc': 'Parity type', 'default': 'none',
102 'values': ('none', 'odd', 'even', 'zero', 'one')},
103 {'id': 'parity_check', 'desc': 'Check parity?', 'default': 'yes',
104 'values': ('yes', 'no')},
105 {'id': 'num_stop_bits', 'desc': 'Stop bits', 'default': 1.0,
106 'values': (0.0, 0.5, 1.0, 1.5)},
107 {'id': 'bit_order', 'desc': 'Bit order', 'default': 'lsb-first',
108 'values': ('lsb-first', 'msb-first')},
109 {'id': 'format', 'desc': 'Data format', 'default': 'hex',
110 'values': ('ascii', 'dec', 'hex', 'oct', 'bin')},
111 {'id': 'invert_rx', 'desc': 'Invert RX?', 'default': 'no',
112 'values': ('yes', 'no')},
113 {'id': 'invert_tx', 'desc': 'Invert TX?', 'default': 'no',
114 'values': ('yes', 'no')},
115 {'id': 'rx_packet_delimiter', 'desc': 'RX packet delimiter (decimal)',
117 {'id': 'tx_packet_delimiter', 'desc': 'TX packet delimiter (decimal)',
119 {'id': 'rx_packet_len', 'desc': 'RX packet length', 'default': -1},
120 {'id': 'tx_packet_len', 'desc': 'TX packet length', 'default': -1},
123 ('rx-data', 'RX data'),
124 ('tx-data', 'TX data'),
125 ('rx-start', 'RX start bits'),
126 ('tx-start', 'TX start bits'),
127 ('rx-parity-ok', 'RX parity OK bits'),
128 ('tx-parity-ok', 'TX parity OK bits'),
129 ('rx-parity-err', 'RX parity error bits'),
130 ('tx-parity-err', 'TX parity error bits'),
131 ('rx-stop', 'RX stop bits'),
132 ('tx-stop', 'TX stop bits'),
133 ('rx-warnings', 'RX warnings'),
134 ('tx-warnings', 'TX warnings'),
135 ('rx-data-bits', 'RX data bits'),
136 ('tx-data-bits', 'TX data bits'),
137 ('rx-break', 'RX break'),
138 ('tx-break', 'TX break'),
139 ('rx-packet', 'RX packet'),
140 ('tx-packet', 'TX packet'),
143 ('rx-data', 'RX', (0, 2, 4, 6, 8)),
144 ('rx-data-bits', 'RX bits', (12,)),
145 ('rx-warnings', 'RX warnings', (10,)),
146 ('rx-break', 'RX break', (14,)),
147 ('rx-packets', 'RX packets', (16,)),
148 ('tx-data', 'TX', (1, 3, 5, 7, 9)),
149 ('tx-data-bits', 'TX bits', (13,)),
150 ('tx-warnings', 'TX warnings', (11,)),
151 ('tx-break', 'TX break', (15,)),
152 ('tx-packets', 'TX packets', (17,)),
157 ('rxtx', 'RX/TX dump'),
159 idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
161 def putx(self, rxtx, data):
162 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
163 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
165 def putx_packet(self, rxtx, data):
166 s, halfbit = self.ss_packet[rxtx], self.bit_width / 2.0
167 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
169 def putpx(self, rxtx, data):
170 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
171 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_python, data)
173 def putg(self, data):
174 s, halfbit = self.samplenum, self.bit_width / 2.0
175 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data)
177 def putp(self, data):
178 s, halfbit = self.samplenum, self.bit_width / 2.0
179 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_python, data)
181 def putgse(self, ss, es, data):
182 self.put(ss, es, self.out_ann, data)
184 def putpse(self, ss, es, data):
185 self.put(ss, es, self.out_python, data)
187 def putbin(self, rxtx, data):
188 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
189 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_binary, data)
195 self.samplerate = None
197 self.frame_start = [-1, -1]
198 self.frame_valid = [None, None]
199 self.startbit = [-1, -1]
200 self.cur_data_bit = [0, 0]
201 self.datavalue = [0, 0]
202 self.paritybit = [-1, -1]
203 self.stopbit1 = [-1, -1]
204 self.startsample = [-1, -1]
205 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
206 self.databits = [[], []]
207 self.break_start = [None, None]
208 self.packet_cache = [[], []]
209 self.ss_packet, self.es_packet = [None, None], [None, None]
210 self.idle_start = [None, None]
213 self.out_python = self.register(srd.OUTPUT_PYTHON)
214 self.out_binary = self.register(srd.OUTPUT_BINARY)
215 self.out_ann = self.register(srd.OUTPUT_ANN)
216 self.bw = (self.options['num_data_bits'] + 7) // 8
218 def metadata(self, key, value):
219 if key == srd.SRD_CONF_SAMPLERATE:
220 self.samplerate = value
221 # The width of one UART bit in number of samples.
222 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
224 def get_sample_point(self, rxtx, bitnum):
225 # Determine absolute sample number of a bit slot's sample point.
226 # bitpos is the samplenumber which is in the middle of the
227 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
228 # (if used) or the first stop bit, and so on).
229 # The samples within bit are 0, 1, ..., (bit_width - 1), therefore
230 # index of the middle sample within bit window is (bit_width - 1) / 2.
231 bitpos = self.frame_start[rxtx] + (self.bit_width - 1) / 2.0
232 bitpos += bitnum * self.bit_width
235 def wait_for_start_bit(self, rxtx, signal):
236 # Save the sample number where the start bit begins.
237 self.frame_start[rxtx] = self.samplenum
238 self.frame_valid[rxtx] = True
240 self.state[rxtx] = 'GET START BIT'
242 def get_start_bit(self, rxtx, signal):
243 self.startbit[rxtx] = signal
245 # The startbit must be 0. If not, we report an error and wait
246 # for the next start bit (assuming this one was spurious).
247 if self.startbit[rxtx] != 0:
248 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
249 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
250 self.frame_valid[rxtx] = False
251 es = self.samplenum + ceil(self.bit_width / 2.0)
252 self.putpse(self.frame_start[rxtx], es, ['FRAME', rxtx,
253 (self.datavalue[rxtx], self.frame_valid[rxtx])])
254 self.state[rxtx] = 'WAIT FOR START BIT'
257 self.cur_data_bit[rxtx] = 0
258 self.datavalue[rxtx] = 0
259 self.startsample[rxtx] = -1
261 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
262 self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
264 self.state[rxtx] = 'GET DATA BITS'
266 def handle_packet(self, rxtx):
267 d = 'rx' if (rxtx == RX) else 'tx'
268 delim = self.options[d + '_packet_delimiter']
269 plen = self.options[d + '_packet_len']
270 if delim == -1 and plen == -1:
273 # Cache data values until we see the delimiter and/or the specified
274 # packet length has been reached (whichever happens first).
275 if len(self.packet_cache[rxtx]) == 0:
276 self.ss_packet[rxtx] = self.startsample[rxtx]
277 self.packet_cache[rxtx].append(self.datavalue[rxtx])
278 if self.datavalue[rxtx] == delim or len(self.packet_cache[rxtx]) == plen:
279 self.es_packet[rxtx] = self.samplenum
281 for b in self.packet_cache[rxtx]:
282 s += self.format_value(b)
283 if self.options['format'] != 'ascii':
285 if self.options['format'] != 'ascii' and s[-1] == ' ':
286 s = s[:-1] # Drop trailing space.
287 self.putx_packet(rxtx, [16 + rxtx, [s]])
288 self.packet_cache[rxtx] = []
290 def get_data_bits(self, rxtx, signal):
291 # Save the sample number of the middle of the first data bit.
292 if self.startsample[rxtx] == -1:
293 self.startsample[rxtx] = self.samplenum
295 self.putg([rxtx + 12, ['%d' % signal]])
297 # Store individual data bits and their start/end samplenumbers.
298 s, halfbit = self.samplenum, int(self.bit_width / 2)
299 self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
301 # Return here, unless we already received all data bits.
302 self.cur_data_bit[rxtx] += 1
303 if self.cur_data_bit[rxtx] < self.options['num_data_bits']:
306 # Convert accumulated data bits to a data value.
307 bits = [b[0] for b in self.databits[rxtx]]
308 if self.options['bit_order'] == 'msb-first':
310 self.datavalue[rxtx] = bitpack(bits)
311 self.putpx(rxtx, ['DATA', rxtx,
312 (self.datavalue[rxtx], self.databits[rxtx])])
314 b = self.datavalue[rxtx]
315 formatted = self.format_value(b)
316 if formatted is not None:
317 self.putx(rxtx, [rxtx, [formatted]])
319 bdata = b.to_bytes(self.bw, byteorder='big')
320 self.putbin(rxtx, [rxtx, bdata])
321 self.putbin(rxtx, [2, bdata])
323 self.handle_packet(rxtx)
325 self.databits[rxtx] = []
327 # Advance to either reception of the parity bit, or reception of
328 # the STOP bits if parity is not applicable.
329 self.state[rxtx] = 'GET PARITY BIT'
330 if self.options['parity_type'] == 'none':
331 self.state[rxtx] = 'GET STOP BITS'
333 def format_value(self, v):
334 # Format value 'v' according to configured options.
335 # Reflects the user selected kind of representation, as well as
336 # the number of data bits in the UART frames.
338 fmt, bits = self.options['format'], self.options['num_data_bits']
340 # Assume "is printable" for values from 32 to including 126,
341 # below 32 is "control" and thus not printable, above 127 is
342 # "not ASCII" in its strict sense, 127 (DEL) is not printable,
343 # fall back to hex representation for non-printables.
345 if v in range(32, 126 + 1):
347 hexfmt = "[{:02X}]" if bits <= 8 else "[{:03X}]"
348 return hexfmt.format(v)
350 # Mere number to text conversion without prefix and padding
351 # for the "decimal" output format.
353 return "{:d}".format(v)
355 # Padding with leading zeroes for hex/oct/bin formats, but
356 # without a prefix for density -- since the format is user
357 # specified, there is no ambiguity.
359 digits = (bits + 4 - 1) // 4
362 digits = (bits + 3 - 1) // 3
369 if fmtchar is not None:
370 fmt = "{{:0{:d}{:s}}}".format(digits, fmtchar)
375 def get_parity_bit(self, rxtx, signal):
376 self.paritybit[rxtx] = signal
378 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
379 self.datavalue[rxtx], self.options['num_data_bits']):
380 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
381 self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
383 # TODO: Return expected/actual parity values.
384 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
385 self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
386 self.frame_valid[rxtx] = False
388 self.state[rxtx] = 'GET STOP BITS'
390 # TODO: Currently only supports 1 stop bit.
391 def get_stop_bits(self, rxtx, signal):
392 self.stopbit1[rxtx] = signal
394 # Stop bits must be 1. If not, we report an error.
395 if self.stopbit1[rxtx] != 1:
396 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
397 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
398 self.frame_valid[rxtx] = False
400 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
401 self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
403 # Pass the complete UART frame to upper layers.
404 es = self.samplenum + ceil(self.bit_width / 2.0)
405 self.putpse(self.frame_start[rxtx], es, ['FRAME', rxtx,
406 (self.datavalue[rxtx], self.frame_valid[rxtx])])
408 self.state[rxtx] = 'WAIT FOR START BIT'
409 self.idle_start[rxtx] = self.frame_start[rxtx] + self.frame_len_sample_count
411 def handle_break(self, rxtx):
412 self.putpse(self.frame_start[rxtx], self.samplenum,
414 self.putgse(self.frame_start[rxtx], self.samplenum,
415 [rxtx + 14, ['Break condition', 'Break', 'Brk', 'B']])
416 self.state[rxtx] = 'WAIT FOR START BIT'
418 def get_wait_cond(self, rxtx, inv):
419 # Return condititions that are suitable for Decoder.wait(). Those
420 # conditions either match the falling edge of the START bit, or
421 # the sample point of the next bit time.
422 state = self.state[rxtx]
423 if state == 'WAIT FOR START BIT':
424 return {rxtx: 'r' if inv else 'f'}
425 if state == 'GET START BIT':
427 elif state == 'GET DATA BITS':
428 bitnum = 1 + self.cur_data_bit[rxtx]
429 elif state == 'GET PARITY BIT':
430 bitnum = 1 + self.options['num_data_bits']
431 elif state == 'GET STOP BITS':
432 bitnum = 1 + self.options['num_data_bits']
433 bitnum += 0 if self.options['parity_type'] == 'none' else 1
434 want_num = ceil(self.get_sample_point(rxtx, bitnum))
435 return {'skip': want_num - self.samplenum}
437 def get_idle_cond(self, rxtx, inv):
438 # Return a condition that corresponds to the (expected) end of
439 # the next frame, assuming that it will be an "idle frame"
440 # (constant high input level for the frame's length).
441 if self.idle_start[rxtx] is None:
443 end_of_frame = self.idle_start[rxtx] + self.frame_len_sample_count
444 if end_of_frame < self.samplenum:
446 return {'skip': end_of_frame - self.samplenum}
448 def inspect_sample(self, rxtx, signal, inv):
449 # Inspect a sample returned by .wait() for the specified UART line.
453 state = self.state[rxtx]
454 if state == 'WAIT FOR START BIT':
455 self.wait_for_start_bit(rxtx, signal)
456 elif state == 'GET START BIT':
457 self.get_start_bit(rxtx, signal)
458 elif state == 'GET DATA BITS':
459 self.get_data_bits(rxtx, signal)
460 elif state == 'GET PARITY BIT':
461 self.get_parity_bit(rxtx, signal)
462 elif state == 'GET STOP BITS':
463 self.get_stop_bits(rxtx, signal)
465 def inspect_edge(self, rxtx, signal, inv):
466 # Inspect edges, independently from traffic, to detect break conditions.
470 # Signal went low. Start another interval.
471 self.break_start[rxtx] = self.samplenum
473 # Signal went high. Was there an extended period with low signal?
474 if self.break_start[rxtx] is None:
476 diff = self.samplenum - self.break_start[rxtx]
477 if diff >= self.break_min_sample_count:
478 self.handle_break(rxtx)
479 self.break_start[rxtx] = None
481 def inspect_idle(self, rxtx, signal, inv):
482 # Check each edge and each period of stable input (either level).
483 # Can derive the "idle frame period has passed" condition.
487 # Low input, cease inspection.
488 self.idle_start[rxtx] = None
490 # High input, either just reached, or still stable.
491 if self.idle_start[rxtx] is None:
492 self.idle_start[rxtx] = self.samplenum
493 diff = self.samplenum - self.idle_start[rxtx]
494 if diff < self.frame_len_sample_count:
496 ss, es = self.idle_start[rxtx], self.samplenum
497 self.putpse(ss, es, ['IDLE', rxtx, 0])
498 self.idle_start[rxtx] = self.samplenum
501 if not self.samplerate:
502 raise SamplerateError('Cannot decode without samplerate.')
504 has_pin = [self.has_channel(ch) for ch in (RX, TX)]
505 if has_pin == [False, False]:
506 raise ChannelError('Either TX or RX (or both) pins required.')
509 inv = [opt['invert_rx'] == 'yes', opt['invert_tx'] == 'yes']
510 cond_data_idx = [None] * len(has_pin)
512 # Determine the number of samples for a complete frame's time span.
513 # A period of low signal (at least) that long is a break condition.
514 frame_samples = 1 # START
515 frame_samples += self.options['num_data_bits']
516 frame_samples += 0 if self.options['parity_type'] == 'none' else 1
517 frame_samples += self.options['num_stop_bits']
518 frame_samples *= self.bit_width
519 self.frame_len_sample_count = ceil(frame_samples)
520 self.break_min_sample_count = self.frame_len_sample_count
521 cond_edge_idx = [None] * len(has_pin)
522 cond_idle_idx = [None] * len(has_pin)
527 cond_data_idx[RX] = len(conds)
528 conds.append(self.get_wait_cond(RX, inv[RX]))
529 cond_edge_idx[RX] = len(conds)
530 conds.append({RX: 'e'})
531 cond_idle_idx[RX] = None
532 idle_cond = self.get_idle_cond(RX, inv[RX])
534 cond_idle_idx[RX] = len(conds)
535 conds.append(idle_cond)
537 cond_data_idx[TX] = len(conds)
538 conds.append(self.get_wait_cond(TX, inv[TX]))
539 cond_edge_idx[TX] = len(conds)
540 conds.append({TX: 'e'})
541 cond_idle_idx[TX] = None
542 idle_cond = self.get_idle_cond(TX, inv[TX])
544 cond_idle_idx[TX] = len(conds)
545 conds.append(idle_cond)
546 (rx, tx) = self.wait(conds)
547 if cond_data_idx[RX] is not None and self.matched[cond_data_idx[RX]]:
548 self.inspect_sample(RX, rx, inv[RX])
549 if cond_edge_idx[RX] is not None and self.matched[cond_edge_idx[RX]]:
550 self.inspect_edge(RX, rx, inv[RX])
551 self.inspect_idle(RX, rx, inv[RX])
552 if cond_idle_idx[RX] is not None and self.matched[cond_idle_idx[RX]]:
553 self.inspect_idle(RX, rx, inv[RX])
554 if cond_data_idx[TX] is not None and self.matched[cond_data_idx[TX]]:
555 self.inspect_sample(TX, tx, inv[TX])
556 if cond_edge_idx[TX] is not None and self.matched[cond_edge_idx[TX]]:
557 self.inspect_edge(TX, tx, inv[TX])
558 self.inspect_idle(TX, tx, inv[TX])
559 if cond_idle_idx[TX] is not None and self.matched[cond_idle_idx[TX]]:
560 self.inspect_idle(TX, tx, inv[TX])