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