]> sigrok.org Git - libsigrokdecode.git/blame_incremental - decoders/uart/pd.py
jtag_ejtag: Shorten a variable name.
[libsigrokdecode.git] / decoders / uart / pd.py
... / ...
CommitLineData
1##
2## This file is part of the libsigrokdecode project.
3##
4## Copyright (C) 2011-2014 Uwe Hermann <uwe@hermann-uwe.de>
5##
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.
10##
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.
15##
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/>.
18##
19
20import sigrokdecode as srd
21from common.srdhelper import bitpack
22from math import floor, ceil
23
24'''
25OUTPUT_PYTHON format:
26
27Packet:
28[<ptype>, <rxtx>, <pdata>]
29
30This 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
45 UART frame.
46
47The <rxtx> field is 0 for RX packets, 1 for TX packets.
48'''
49
50# Used for differentiating between the two data directions.
51RX = 0
52TX = 1
53
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'.
58def parity_ok(parity_type, parity_bit, data, num_data_bits):
59
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
65
66 # Count number of 1 (high) bits in the data (and the parity bit itself!).
67 ones = bin(data).count('1') + parity_bit
68
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
74
75class SamplerateError(Exception):
76 pass
77
78class ChannelError(Exception):
79 pass
80
81class Decoder(srd.Decoder):
82 api_version = 3
83 id = 'uart'
84 name = 'UART'
85 longname = 'Universal Asynchronous Receiver/Transmitter'
86 desc = 'Asynchronous, serial bus.'
87 license = 'gplv2+'
88 inputs = ['logic']
89 outputs = ['uart']
90 optional_channels = (
91 # Allow specifying only one of the signals, e.g. if only one data
92 # direction exists (or is relevant).
93 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
94 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
95 )
96 options = (
97 {'id': 'baudrate', 'desc': 'Baud rate', 'default': 115200},
98 {'id': 'num_data_bits', 'desc': 'Data bits', 'default': 8,
99 'values': (5, 6, 7, 8, 9)},
100 {'id': 'parity_type', 'desc': 'Parity type', 'default': 'none',
101 'values': ('none', 'odd', 'even', 'zero', 'one')},
102 {'id': 'parity_check', 'desc': 'Check parity?', 'default': 'yes',
103 'values': ('yes', 'no')},
104 {'id': 'num_stop_bits', 'desc': 'Stop bits', 'default': 1.0,
105 'values': (0.0, 0.5, 1.0, 1.5)},
106 {'id': 'bit_order', 'desc': 'Bit order', 'default': 'lsb-first',
107 'values': ('lsb-first', 'msb-first')},
108 {'id': 'format', 'desc': 'Data format', 'default': 'hex',
109 'values': ('ascii', 'dec', 'hex', 'oct', 'bin')},
110 {'id': 'invert_rx', 'desc': 'Invert RX?', 'default': 'no',
111 'values': ('yes', 'no')},
112 {'id': 'invert_tx', 'desc': 'Invert TX?', 'default': 'no',
113 'values': ('yes', 'no')},
114 )
115 annotations = (
116 ('rx-data', 'RX data'),
117 ('tx-data', 'TX data'),
118 ('rx-start', 'RX start bits'),
119 ('tx-start', 'TX start bits'),
120 ('rx-parity-ok', 'RX parity OK bits'),
121 ('tx-parity-ok', 'TX parity OK bits'),
122 ('rx-parity-err', 'RX parity error bits'),
123 ('tx-parity-err', 'TX parity error bits'),
124 ('rx-stop', 'RX stop bits'),
125 ('tx-stop', 'TX stop bits'),
126 ('rx-warnings', 'RX warnings'),
127 ('tx-warnings', 'TX warnings'),
128 ('rx-data-bits', 'RX data bits'),
129 ('tx-data-bits', 'TX data bits'),
130 ('rx-break', 'RX break'),
131 ('tx-break', 'TX break'),
132 )
133 annotation_rows = (
134 ('rx-data', 'RX', (0, 2, 4, 6, 8)),
135 ('rx-data-bits', 'RX bits', (12,)),
136 ('rx-warnings', 'RX warnings', (10,)),
137 ('rx-break', 'RX break', (14,)),
138 ('tx-data', 'TX', (1, 3, 5, 7, 9)),
139 ('tx-data-bits', 'TX bits', (13,)),
140 ('tx-warnings', 'TX warnings', (11,)),
141 ('tx-break', 'TX break', (15,)),
142 )
143 binary = (
144 ('rx', 'RX dump'),
145 ('tx', 'TX dump'),
146 ('rxtx', 'RX/TX dump'),
147 )
148 idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
149
150 def putx(self, rxtx, data):
151 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
152 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
153
154 def putpx(self, rxtx, data):
155 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
156 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_python, data)
157
158 def putg(self, data):
159 s, halfbit = self.samplenum, self.bit_width / 2.0
160 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data)
161
162 def putp(self, data):
163 s, halfbit = self.samplenum, self.bit_width / 2.0
164 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_python, data)
165
166 def putgse(self, ss, es, data):
167 self.put(ss, es, self.out_ann, data)
168
169 def putpse(self, ss, es, data):
170 self.put(ss, es, self.out_python, data)
171
172 def putbin(self, rxtx, data):
173 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
174 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_binary, data)
175
176 def __init__(self):
177 self.reset()
178
179 def reset(self):
180 self.samplerate = None
181 self.samplenum = 0
182 self.frame_start = [-1, -1]
183 self.frame_valid = [None, None]
184 self.startbit = [-1, -1]
185 self.cur_data_bit = [0, 0]
186 self.datavalue = [0, 0]
187 self.paritybit = [-1, -1]
188 self.stopbit1 = [-1, -1]
189 self.startsample = [-1, -1]
190 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
191 self.databits = [[], []]
192 self.break_start = [None, None]
193
194 def start(self):
195 self.out_python = self.register(srd.OUTPUT_PYTHON)
196 self.out_binary = self.register(srd.OUTPUT_BINARY)
197 self.out_ann = self.register(srd.OUTPUT_ANN)
198 self.bw = (self.options['num_data_bits'] + 7) // 8
199
200 def metadata(self, key, value):
201 if key == srd.SRD_CONF_SAMPLERATE:
202 self.samplerate = value
203 # The width of one UART bit in number of samples.
204 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
205
206 def get_sample_point(self, rxtx, bitnum):
207 # Determine absolute sample number of a bit slot's sample point.
208 # bitpos is the samplenumber which is in the middle of the
209 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
210 # (if used) or the first stop bit, and so on).
211 # The samples within bit are 0, 1, ..., (bit_width - 1), therefore
212 # index of the middle sample within bit window is (bit_width - 1) / 2.
213 bitpos = self.frame_start[rxtx] + (self.bit_width - 1) / 2.0
214 bitpos += bitnum * self.bit_width
215 return bitpos
216
217 def wait_for_start_bit(self, rxtx, signal):
218 # Save the sample number where the start bit begins.
219 self.frame_start[rxtx] = self.samplenum
220 self.frame_valid[rxtx] = True
221
222 self.state[rxtx] = 'GET START BIT'
223
224 def get_start_bit(self, rxtx, signal):
225 self.startbit[rxtx] = signal
226
227 # The startbit must be 0. If not, we report an error and wait
228 # for the next start bit (assuming this one was spurious).
229 if self.startbit[rxtx] != 0:
230 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
231 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
232 self.frame_valid[rxtx] = False
233 es = self.samplenum + ceil(self.bit_width / 2.0)
234 self.putpse(self.frame_start[rxtx], es, ['FRAME', rxtx,
235 (self.datavalue[rxtx], self.frame_valid[rxtx])])
236 self.state[rxtx] = 'WAIT FOR START BIT'
237 return
238
239 self.cur_data_bit[rxtx] = 0
240 self.datavalue[rxtx] = 0
241 self.startsample[rxtx] = -1
242
243 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
244 self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
245
246 self.state[rxtx] = 'GET DATA BITS'
247
248 def get_data_bits(self, rxtx, signal):
249 # Save the sample number of the middle of the first data bit.
250 if self.startsample[rxtx] == -1:
251 self.startsample[rxtx] = self.samplenum
252
253 self.putg([rxtx + 12, ['%d' % signal]])
254
255 # Store individual data bits and their start/end samplenumbers.
256 s, halfbit = self.samplenum, int(self.bit_width / 2)
257 self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
258
259 # Return here, unless we already received all data bits.
260 self.cur_data_bit[rxtx] += 1
261 if self.cur_data_bit[rxtx] < self.options['num_data_bits']:
262 return
263
264 # Convert accumulated data bits to a data value.
265 bits = [b[0] for b in self.databits[rxtx]]
266 if self.options['bit_order'] == 'msb-first':
267 bits.reverse()
268 self.datavalue[rxtx] = bitpack(bits)
269 self.putpx(rxtx, ['DATA', rxtx,
270 (self.datavalue[rxtx], self.databits[rxtx])])
271
272 b = self.datavalue[rxtx]
273 formatted = self.format_value(b)
274 if formatted is not None:
275 self.putx(rxtx, [rxtx, [formatted]])
276
277 bdata = b.to_bytes(self.bw, byteorder='big')
278 self.putbin(rxtx, [rxtx, bdata])
279 self.putbin(rxtx, [2, bdata])
280
281 self.databits[rxtx] = []
282
283 # Advance to either reception of the parity bit, or reception of
284 # the STOP bits if parity is not applicable.
285 self.state[rxtx] = 'GET PARITY BIT'
286 if self.options['parity_type'] == 'none':
287 self.state[rxtx] = 'GET STOP BITS'
288
289 def format_value(self, v):
290 # Format value 'v' according to configured options.
291 # Reflects the user selected kind of representation, as well as
292 # the number of data bits in the UART frames.
293
294 fmt, bits = self.options['format'], self.options['num_data_bits']
295
296 # Assume "is printable" for values from 32 to including 126,
297 # below 32 is "control" and thus not printable, above 127 is
298 # "not ASCII" in its strict sense, 127 (DEL) is not printable,
299 # fall back to hex representation for non-printables.
300 if fmt == 'ascii':
301 if v in range(32, 126 + 1):
302 return chr(v)
303 hexfmt = "[{:02X}]" if bits <= 8 else "[{:03X}]"
304 return hexfmt.format(v)
305
306 # Mere number to text conversion without prefix and padding
307 # for the "decimal" output format.
308 if fmt == 'dec':
309 return "{:d}".format(v)
310
311 # Padding with leading zeroes for hex/oct/bin formats, but
312 # without a prefix for density -- since the format is user
313 # specified, there is no ambiguity.
314 if fmt == 'hex':
315 digits = (bits + 4 - 1) // 4
316 fmtchar = "X"
317 elif fmt == 'oct':
318 digits = (bits + 3 - 1) // 3
319 fmtchar = "o"
320 elif fmt == 'bin':
321 digits = bits
322 fmtchar = "b"
323 else:
324 fmtchar = None
325 if fmtchar is not None:
326 fmt = "{{:0{:d}{:s}}}".format(digits, fmtchar)
327 return fmt.format(v)
328
329 return None
330
331 def get_parity_bit(self, rxtx, signal):
332 self.paritybit[rxtx] = signal
333
334 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
335 self.datavalue[rxtx], self.options['num_data_bits']):
336 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
337 self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
338 else:
339 # TODO: Return expected/actual parity values.
340 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
341 self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
342 self.frame_valid[rxtx] = False
343
344 self.state[rxtx] = 'GET STOP BITS'
345
346 # TODO: Currently only supports 1 stop bit.
347 def get_stop_bits(self, rxtx, signal):
348 self.stopbit1[rxtx] = signal
349
350 # Stop bits must be 1. If not, we report an error.
351 if self.stopbit1[rxtx] != 1:
352 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
353 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
354 self.frame_valid[rxtx] = False
355
356 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
357 self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
358
359 # Pass the complete UART frame to upper layers.
360 es = self.samplenum + ceil(self.bit_width / 2.0)
361 self.putpse(self.frame_start[rxtx], es, ['FRAME', rxtx,
362 (self.datavalue[rxtx], self.frame_valid[rxtx])])
363
364 self.state[rxtx] = 'WAIT FOR START BIT'
365
366 def handle_break(self, rxtx):
367 self.putpse(self.frame_start[rxtx], self.samplenum,
368 ['BREAK', rxtx, 0])
369 self.putgse(self.frame_start[rxtx], self.samplenum,
370 [rxtx + 14, ['Break condition', 'Break', 'Brk', 'B']])
371 self.state[rxtx] = 'WAIT FOR START BIT'
372
373 def get_wait_cond(self, rxtx, inv):
374 # Return condititions that are suitable for Decoder.wait(). Those
375 # conditions either match the falling edge of the START bit, or
376 # the sample point of the next bit time.
377 state = self.state[rxtx]
378 if state == 'WAIT FOR START BIT':
379 return {rxtx: 'r' if inv else 'f'}
380 if state == 'GET START BIT':
381 bitnum = 0
382 elif state == 'GET DATA BITS':
383 bitnum = 1 + self.cur_data_bit[rxtx]
384 elif state == 'GET PARITY BIT':
385 bitnum = 1 + self.options['num_data_bits']
386 elif state == 'GET STOP BITS':
387 bitnum = 1 + self.options['num_data_bits']
388 bitnum += 0 if self.options['parity_type'] == 'none' else 1
389 want_num = ceil(self.get_sample_point(rxtx, bitnum))
390 return {'skip': want_num - self.samplenum}
391
392 def inspect_sample(self, rxtx, signal, inv):
393 # Inspect a sample returned by .wait() for the specified UART line.
394 if inv:
395 signal = not signal
396
397 state = self.state[rxtx]
398 if state == 'WAIT FOR START BIT':
399 self.wait_for_start_bit(rxtx, signal)
400 elif state == 'GET START BIT':
401 self.get_start_bit(rxtx, signal)
402 elif state == 'GET DATA BITS':
403 self.get_data_bits(rxtx, signal)
404 elif state == 'GET PARITY BIT':
405 self.get_parity_bit(rxtx, signal)
406 elif state == 'GET STOP BITS':
407 self.get_stop_bits(rxtx, signal)
408
409 def inspect_edge(self, rxtx, signal, inv):
410 # Inspect edges, independently from traffic, to detect break conditions.
411 if inv:
412 signal = not signal
413 if not signal:
414 # Signal went low. Start another interval.
415 self.break_start[rxtx] = self.samplenum
416 return
417 # Signal went high. Was there an extended period with low signal?
418 if self.break_start[rxtx] is None:
419 return
420 diff = self.samplenum - self.break_start[rxtx]
421 if diff >= self.break_min_sample_count:
422 self.handle_break(rxtx)
423 self.break_start[rxtx] = None
424
425 def decode(self):
426 if not self.samplerate:
427 raise SamplerateError('Cannot decode without samplerate.')
428
429 has_pin = [self.has_channel(ch) for ch in (RX, TX)]
430 if has_pin == [False, False]:
431 raise ChannelError('Either TX or RX (or both) pins required.')
432
433 opt = self.options
434 inv = [opt['invert_rx'] == 'yes', opt['invert_tx'] == 'yes']
435 cond_data_idx = [None] * len(has_pin)
436
437 # Determine the number of samples for a complete frame's time span.
438 # A period of low signal (at least) that long is a break condition.
439 frame_samples = 1 # START
440 frame_samples += self.options['num_data_bits']
441 frame_samples += 0 if self.options['parity_type'] == 'none' else 1
442 frame_samples += self.options['num_stop_bits']
443 frame_samples *= self.bit_width
444 self.break_min_sample_count = ceil(frame_samples)
445 cond_edge_idx = [None] * len(has_pin)
446
447 while True:
448 conds = []
449 if has_pin[RX]:
450 cond_data_idx[RX] = len(conds)
451 conds.append(self.get_wait_cond(RX, inv[RX]))
452 cond_edge_idx[RX] = len(conds)
453 conds.append({RX: 'e'})
454 if has_pin[TX]:
455 cond_data_idx[TX] = len(conds)
456 conds.append(self.get_wait_cond(TX, inv[TX]))
457 cond_edge_idx[TX] = len(conds)
458 conds.append({TX: 'e'})
459 (rx, tx) = self.wait(conds)
460 if cond_data_idx[RX] is not None and self.matched[cond_data_idx[RX]]:
461 self.inspect_sample(RX, rx, inv[RX])
462 if cond_edge_idx[RX] is not None and self.matched[cond_edge_idx[RX]]:
463 self.inspect_edge(RX, rx, inv[RX])
464 if cond_data_idx[TX] is not None and self.matched[cond_data_idx[TX]]:
465 self.inspect_sample(TX, tx, inv[TX])
466 if cond_edge_idx[TX] is not None and self.matched[cond_edge_idx[TX]]:
467 self.inspect_edge(TX, tx, inv[TX])