]> sigrok.org Git - libsigrokdecode.git/blob - decoders/uart/pd.py
uart: Add [rx|tx]_packet_len options.
[libsigrokdecode.git] / decoders / uart / pd.py
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
20 import sigrokdecode as srd
21 from common.srdhelper import bitpack
22 from math import floor, ceil
23
24 '''
25 OUTPUT_PYTHON format:
26
27 Packet:
28 [<ptype>, <rxtx>, <pdata>]
29
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
45    UART frame.
46
47 The <rxtx> field is 0 for RX packets, 1 for TX packets.
48 '''
49
50 # Used for differentiating between the two data directions.
51 RX = 0
52 TX = 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'.
58 def 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
75 class SamplerateError(Exception):
76     pass
77
78 class ChannelError(Exception):
79     pass
80
81 class 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     tags = ['Embedded/industrial']
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         {'id': 'rx_packet_delimiter', 'desc': 'RX packet delimiter (decimal)',
116             'default': -1},
117         {'id': 'tx_packet_delimiter', 'desc': 'TX packet delimiter (decimal)',
118             'default': -1},
119         {'id': 'rx_packet_len', 'desc': 'RX packet length', 'default': -1},
120         {'id': 'tx_packet_len', 'desc': 'TX packet length', 'default': -1},
121     )
122     annotations = (
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'),
141     )
142     annotation_rows = (
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,)),
153     )
154     binary = (
155         ('rx', 'RX dump'),
156         ('tx', 'TX dump'),
157         ('rxtx', 'RX/TX dump'),
158     )
159     idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
160
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)
164
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)
168
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)
172
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)
176
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)
180
181     def putgse(self, ss, es, data):
182         self.put(ss, es, self.out_ann, data)
183
184     def putpse(self, ss, es, data):
185         self.put(ss, es, self.out_python, data)
186
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)
190
191     def __init__(self):
192         self.reset()
193
194     def reset(self):
195         self.samplerate = None
196         self.samplenum = 0
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
211     def start(self):
212         self.out_python = self.register(srd.OUTPUT_PYTHON)
213         self.out_binary = self.register(srd.OUTPUT_BINARY)
214         self.out_ann = self.register(srd.OUTPUT_ANN)
215         self.bw = (self.options['num_data_bits'] + 7) // 8
216
217     def metadata(self, key, value):
218         if key == srd.SRD_CONF_SAMPLERATE:
219             self.samplerate = value
220             # The width of one UART bit in number of samples.
221             self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
222
223     def get_sample_point(self, rxtx, bitnum):
224         # Determine absolute sample number of a bit slot's sample point.
225         # bitpos is the samplenumber which is in the middle of the
226         # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
227         # (if used) or the first stop bit, and so on).
228         # The samples within bit are 0, 1, ..., (bit_width - 1), therefore
229         # index of the middle sample within bit window is (bit_width - 1) / 2.
230         bitpos = self.frame_start[rxtx] + (self.bit_width - 1) / 2.0
231         bitpos += bitnum * self.bit_width
232         return bitpos
233
234     def wait_for_start_bit(self, rxtx, signal):
235         # Save the sample number where the start bit begins.
236         self.frame_start[rxtx] = self.samplenum
237         self.frame_valid[rxtx] = True
238
239         self.state[rxtx] = 'GET START BIT'
240
241     def get_start_bit(self, rxtx, signal):
242         self.startbit[rxtx] = signal
243
244         # The startbit must be 0. If not, we report an error and wait
245         # for the next start bit (assuming this one was spurious).
246         if self.startbit[rxtx] != 0:
247             self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
248             self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
249             self.frame_valid[rxtx] = False
250             es = self.samplenum + ceil(self.bit_width / 2.0)
251             self.putpse(self.frame_start[rxtx], es, ['FRAME', rxtx,
252                 (self.datavalue[rxtx], self.frame_valid[rxtx])])
253             self.state[rxtx] = 'WAIT FOR START BIT'
254             return
255
256         self.cur_data_bit[rxtx] = 0
257         self.datavalue[rxtx] = 0
258         self.startsample[rxtx] = -1
259
260         self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
261         self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
262
263         self.state[rxtx] = 'GET DATA BITS'
264
265     def handle_packet(self, rxtx):
266         d = 'rx' if (rxtx == RX) else 'tx'
267         delim = self.options[d + '_packet_delimiter']
268         plen = self.options[d + '_packet_len']
269         if delim == -1 and plen == -1:
270             return
271
272         # Cache data values until we see the delimiter and/or the specified
273         # packet length has been reached (whichever happens first).
274         if len(self.packet_cache[rxtx]) == 0:
275             self.ss_packet[rxtx] = self.startsample[rxtx]
276         self.packet_cache[rxtx].append(self.datavalue[rxtx])
277         if self.datavalue[rxtx] == delim or len(self.packet_cache[rxtx]) == plen:
278             self.es_packet[rxtx] = self.samplenum
279             s = ''
280             for b in self.packet_cache[rxtx]:
281                 s += self.format_value(b)
282                 if self.options['format'] != 'ascii':
283                     s += ' '
284             if self.options['format'] != 'ascii' and s[-1] == ' ':
285                 s = s[:-1] # Drop trailing space.
286             self.putx_packet(rxtx, [16 + rxtx, [s]])
287             self.packet_cache[rxtx] = []
288
289     def get_data_bits(self, rxtx, signal):
290         # Save the sample number of the middle of the first data bit.
291         if self.startsample[rxtx] == -1:
292             self.startsample[rxtx] = self.samplenum
293
294         self.putg([rxtx + 12, ['%d' % signal]])
295
296         # Store individual data bits and their start/end samplenumbers.
297         s, halfbit = self.samplenum, int(self.bit_width / 2)
298         self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
299
300         # Return here, unless we already received all data bits.
301         self.cur_data_bit[rxtx] += 1
302         if self.cur_data_bit[rxtx] < self.options['num_data_bits']:
303             return
304
305         # Convert accumulated data bits to a data value.
306         bits = [b[0] for b in self.databits[rxtx]]
307         if self.options['bit_order'] == 'msb-first':
308             bits.reverse()
309         self.datavalue[rxtx] = bitpack(bits)
310         self.putpx(rxtx, ['DATA', rxtx,
311             (self.datavalue[rxtx], self.databits[rxtx])])
312
313         b = self.datavalue[rxtx]
314         formatted = self.format_value(b)
315         if formatted is not None:
316             self.putx(rxtx, [rxtx, [formatted]])
317
318         bdata = b.to_bytes(self.bw, byteorder='big')
319         self.putbin(rxtx, [rxtx, bdata])
320         self.putbin(rxtx, [2, bdata])
321
322         self.handle_packet(rxtx)
323
324         self.databits[rxtx] = []
325
326         # Advance to either reception of the parity bit, or reception of
327         # the STOP bits if parity is not applicable.
328         self.state[rxtx] = 'GET PARITY BIT'
329         if self.options['parity_type'] == 'none':
330             self.state[rxtx] = 'GET STOP BITS'
331
332     def format_value(self, v):
333         # Format value 'v' according to configured options.
334         # Reflects the user selected kind of representation, as well as
335         # the number of data bits in the UART frames.
336
337         fmt, bits = self.options['format'], self.options['num_data_bits']
338
339         # Assume "is printable" for values from 32 to including 126,
340         # below 32 is "control" and thus not printable, above 127 is
341         # "not ASCII" in its strict sense, 127 (DEL) is not printable,
342         # fall back to hex representation for non-printables.
343         if fmt == 'ascii':
344             if v in range(32, 126 + 1):
345                 return chr(v)
346             hexfmt = "[{:02X}]" if bits <= 8 else "[{:03X}]"
347             return hexfmt.format(v)
348
349         # Mere number to text conversion without prefix and padding
350         # for the "decimal" output format.
351         if fmt == 'dec':
352             return "{:d}".format(v)
353
354         # Padding with leading zeroes for hex/oct/bin formats, but
355         # without a prefix for density -- since the format is user
356         # specified, there is no ambiguity.
357         if fmt == 'hex':
358             digits = (bits + 4 - 1) // 4
359             fmtchar = "X"
360         elif fmt == 'oct':
361             digits = (bits + 3 - 1) // 3
362             fmtchar = "o"
363         elif fmt == 'bin':
364             digits = bits
365             fmtchar = "b"
366         else:
367             fmtchar = None
368         if fmtchar is not None:
369             fmt = "{{:0{:d}{:s}}}".format(digits, fmtchar)
370             return fmt.format(v)
371
372         return None
373
374     def get_parity_bit(self, rxtx, signal):
375         self.paritybit[rxtx] = signal
376
377         if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
378                      self.datavalue[rxtx], self.options['num_data_bits']):
379             self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
380             self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
381         else:
382             # TODO: Return expected/actual parity values.
383             self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
384             self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
385             self.frame_valid[rxtx] = False
386
387         self.state[rxtx] = 'GET STOP BITS'
388
389     # TODO: Currently only supports 1 stop bit.
390     def get_stop_bits(self, rxtx, signal):
391         self.stopbit1[rxtx] = signal
392
393         # Stop bits must be 1. If not, we report an error.
394         if self.stopbit1[rxtx] != 1:
395             self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
396             self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
397             self.frame_valid[rxtx] = False
398
399         self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
400         self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
401
402         # Pass the complete UART frame to upper layers.
403         es = self.samplenum + ceil(self.bit_width / 2.0)
404         self.putpse(self.frame_start[rxtx], es, ['FRAME', rxtx,
405             (self.datavalue[rxtx], self.frame_valid[rxtx])])
406
407         self.state[rxtx] = 'WAIT FOR START BIT'
408
409     def handle_break(self, rxtx):
410         self.putpse(self.frame_start[rxtx], self.samplenum,
411                 ['BREAK', rxtx, 0])
412         self.putgse(self.frame_start[rxtx], self.samplenum,
413                 [rxtx + 14, ['Break condition', 'Break', 'Brk', 'B']])
414         self.state[rxtx] = 'WAIT FOR START BIT'
415
416     def get_wait_cond(self, rxtx, inv):
417         # Return condititions that are suitable for Decoder.wait(). Those
418         # conditions either match the falling edge of the START bit, or
419         # the sample point of the next bit time.
420         state = self.state[rxtx]
421         if state == 'WAIT FOR START BIT':
422             return {rxtx: 'r' if inv else 'f'}
423         if state == 'GET START BIT':
424             bitnum = 0
425         elif state == 'GET DATA BITS':
426             bitnum = 1 + self.cur_data_bit[rxtx]
427         elif state == 'GET PARITY BIT':
428             bitnum = 1 + self.options['num_data_bits']
429         elif state == 'GET STOP BITS':
430             bitnum = 1 + self.options['num_data_bits']
431             bitnum += 0 if self.options['parity_type'] == 'none' else 1
432         want_num = ceil(self.get_sample_point(rxtx, bitnum))
433         return {'skip': want_num - self.samplenum}
434
435     def inspect_sample(self, rxtx, signal, inv):
436         # Inspect a sample returned by .wait() for the specified UART line.
437         if inv:
438             signal = not signal
439
440         state = self.state[rxtx]
441         if state == 'WAIT FOR START BIT':
442             self.wait_for_start_bit(rxtx, signal)
443         elif state == 'GET START BIT':
444             self.get_start_bit(rxtx, signal)
445         elif state == 'GET DATA BITS':
446             self.get_data_bits(rxtx, signal)
447         elif state == 'GET PARITY BIT':
448             self.get_parity_bit(rxtx, signal)
449         elif state == 'GET STOP BITS':
450             self.get_stop_bits(rxtx, signal)
451
452     def inspect_edge(self, rxtx, signal, inv):
453         # Inspect edges, independently from traffic, to detect break conditions.
454         if inv:
455             signal = not signal
456         if not signal:
457             # Signal went low. Start another interval.
458             self.break_start[rxtx] = self.samplenum
459             return
460         # Signal went high. Was there an extended period with low signal?
461         if self.break_start[rxtx] is None:
462             return
463         diff = self.samplenum - self.break_start[rxtx]
464         if diff >= self.break_min_sample_count:
465             self.handle_break(rxtx)
466         self.break_start[rxtx] = None
467
468     def decode(self):
469         if not self.samplerate:
470             raise SamplerateError('Cannot decode without samplerate.')
471
472         has_pin = [self.has_channel(ch) for ch in (RX, TX)]
473         if has_pin == [False, False]:
474             raise ChannelError('Either TX or RX (or both) pins required.')
475
476         opt = self.options
477         inv = [opt['invert_rx'] == 'yes', opt['invert_tx'] == 'yes']
478         cond_data_idx = [None] * len(has_pin)
479
480         # Determine the number of samples for a complete frame's time span.
481         # A period of low signal (at least) that long is a break condition.
482         frame_samples = 1 # START
483         frame_samples += self.options['num_data_bits']
484         frame_samples += 0 if self.options['parity_type'] == 'none' else 1
485         frame_samples += self.options['num_stop_bits']
486         frame_samples *= self.bit_width
487         self.break_min_sample_count = ceil(frame_samples)
488         cond_edge_idx = [None] * len(has_pin)
489
490         while True:
491             conds = []
492             if has_pin[RX]:
493                 cond_data_idx[RX] = len(conds)
494                 conds.append(self.get_wait_cond(RX, inv[RX]))
495                 cond_edge_idx[RX] = len(conds)
496                 conds.append({RX: 'e'})
497             if has_pin[TX]:
498                 cond_data_idx[TX] = len(conds)
499                 conds.append(self.get_wait_cond(TX, inv[TX]))
500                 cond_edge_idx[TX] = len(conds)
501                 conds.append({TX: 'e'})
502             (rx, tx) = self.wait(conds)
503             if cond_data_idx[RX] is not None and self.matched[cond_data_idx[RX]]:
504                 self.inspect_sample(RX, rx, inv[RX])
505             if cond_edge_idx[RX] is not None and self.matched[cond_edge_idx[RX]]:
506                 self.inspect_edge(RX, rx, inv[RX])
507             if cond_data_idx[TX] is not None and self.matched[cond_data_idx[TX]]:
508                 self.inspect_sample(TX, tx, inv[TX])
509             if cond_edge_idx[TX] is not None and self.matched[cond_edge_idx[TX]]:
510                 self.inspect_edge(TX, tx, inv[TX])