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