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