]> sigrok.org Git - libsigrokdecode.git/blob - decoders/uart/pd.py
0fa0e7ff442b8e307a883cbd9711b646be9372cd
[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, write to the Free Software
18 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19 ##
20
21 import sigrokdecode as srd
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
44 The <rxtx> field is 0 for RX packets, 1 for TX packets.
45 '''
46
47 # Used for differentiating between the two data directions.
48 RX = 0
49 TX = 1
50
51 # Given a parity type to check (odd, even, zero, one), the value of the
52 # parity bit, the value of the data, and the length of the data (5-9 bits,
53 # usually 8 bits) return True if the parity is correct, False otherwise.
54 # 'none' is _not_ allowed as value for 'parity_type'.
55 def parity_ok(parity_type, parity_bit, data, num_data_bits):
56
57     # Handle easy cases first (parity bit is always 1 or 0).
58     if parity_type == 'zero':
59         return parity_bit == 0
60     elif parity_type == 'one':
61         return parity_bit == 1
62
63     # Count number of 1 (high) bits in the data (and the parity bit itself!).
64     ones = bin(data).count('1') + parity_bit
65
66     # Check for odd/even parity.
67     if parity_type == 'odd':
68         return (ones % 2) == 1
69     elif parity_type == 'even':
70         return (ones % 2) == 0
71
72 class SamplerateError(Exception):
73     pass
74
75 class ChannelError(Exception):
76     pass
77
78 class Decoder(srd.Decoder):
79     api_version = 2
80     id = 'uart'
81     name = 'UART'
82     longname = 'Universal Asynchronous Receiver/Transmitter'
83     desc = 'Asynchronous, serial bus.'
84     license = 'gplv2+'
85     inputs = ['logic']
86     outputs = ['uart']
87     optional_channels = (
88         # Allow specifying only one of the signals, e.g. if only one data
89         # direction exists (or is relevant).
90         {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
91         {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
92     )
93     options = (
94         {'id': 'baudrate', 'desc': 'Baud rate', 'default': 115200},
95         {'id': 'num_data_bits', 'desc': 'Data bits', 'default': 8,
96             'values': (5, 6, 7, 8, 9)},
97         {'id': 'parity_type', 'desc': 'Parity type', 'default': 'none',
98             'values': ('none', 'odd', 'even', 'zero', 'one')},
99         {'id': 'parity_check', 'desc': 'Check parity?', 'default': 'yes',
100             'values': ('yes', 'no')},
101         {'id': 'num_stop_bits', 'desc': 'Stop bits', 'default': 1.0,
102             'values': (0.0, 0.5, 1.0, 1.5)},
103         {'id': 'bit_order', 'desc': 'Bit order', 'default': 'lsb-first',
104             'values': ('lsb-first', 'msb-first')},
105         {'id': 'format', 'desc': 'Data format', 'default': 'hex',
106             'values': ('ascii', 'dec', 'hex', 'oct', 'bin')},
107         {'id': 'invert_rx', 'desc': 'Invert RX?', 'default': 'no',
108             'values': ('yes', 'no')},
109         {'id': 'invert_tx', 'desc': 'Invert TX?', 'default': 'no',
110             'values': ('yes', 'no')},
111     )
112     annotations = (
113         ('rx-data', 'RX data'),
114         ('tx-data', 'TX data'),
115         ('rx-start', 'RX start bits'),
116         ('tx-start', 'TX start bits'),
117         ('rx-parity-ok', 'RX parity OK bits'),
118         ('tx-parity-ok', 'TX parity OK bits'),
119         ('rx-parity-err', 'RX parity error bits'),
120         ('tx-parity-err', 'TX parity error bits'),
121         ('rx-stop', 'RX stop bits'),
122         ('tx-stop', 'TX stop bits'),
123         ('rx-warnings', 'RX warnings'),
124         ('tx-warnings', 'TX warnings'),
125         ('rx-data-bits', 'RX data bits'),
126         ('tx-data-bits', 'TX data bits'),
127     )
128     annotation_rows = (
129         ('rx-data', 'RX', (0, 2, 4, 6, 8)),
130         ('rx-data-bits', 'RX bits', (12,)),
131         ('rx-warnings', 'RX warnings', (10,)),
132         ('tx-data', 'TX', (1, 3, 5, 7, 9)),
133         ('tx-data-bits', 'TX bits', (13,)),
134         ('tx-warnings', 'TX warnings', (11,)),
135     )
136     binary = (
137         ('rx', 'RX dump'),
138         ('tx', 'TX dump'),
139         ('rxtx', 'RX/TX dump'),
140     )
141     idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
142
143     def putx(self, rxtx, data):
144         s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
145         self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
146
147     def putpx(self, rxtx, data):
148         s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
149         self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_python, data)
150
151     def putg(self, data):
152         s, halfbit = self.samplenum, self.bit_width / 2.0
153         self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data)
154
155     def putp(self, data):
156         s, halfbit = self.samplenum, self.bit_width / 2.0
157         self.put(s - floor(halfbit), s + ceil(halfbit), self.out_python, data)
158
159     def putbin(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_binary, data)
162
163     def __init__(self):
164         self.samplerate = None
165         self.samplenum = 0
166         self.frame_start = [-1, -1]
167         self.startbit = [-1, -1]
168         self.cur_data_bit = [0, 0]
169         self.datavalue = [0, 0]
170         self.paritybit = [-1, -1]
171         self.stopbit1 = [-1, -1]
172         self.startsample = [-1, -1]
173         self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
174         self.oldbit = [1, 1]
175         self.oldpins = [-1, -1]
176         self.databits = [[], []]
177
178     def start(self):
179         self.out_python = self.register(srd.OUTPUT_PYTHON)
180         self.out_binary = self.register(srd.OUTPUT_BINARY)
181         self.out_ann = self.register(srd.OUTPUT_ANN)
182         self.bw = (self.options['num_data_bits'] + 7) // 8
183
184     def metadata(self, key, value):
185         if key == srd.SRD_CONF_SAMPLERATE:
186             self.samplerate = value
187             # The width of one UART bit in number of samples.
188             self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
189
190     # Return true if we reached the middle of the desired bit, false otherwise.
191     def reached_bit(self, rxtx, bitnum):
192         # bitpos is the samplenumber which is in the middle of the
193         # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
194         # (if used) or the first stop bit, and so on).
195         # The samples within bit are 0, 1, ..., (bit_width - 1), therefore
196         # index of the middle sample within bit window is (bit_width - 1) / 2.
197         bitpos = self.frame_start[rxtx] + (self.bit_width - 1) / 2.0
198         bitpos += bitnum * self.bit_width
199         if self.samplenum >= bitpos:
200             return True
201         return False
202
203     def reached_bit_last(self, rxtx, bitnum):
204         bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
205         if self.samplenum >= bitpos:
206             return True
207         return False
208
209     def wait_for_start_bit(self, rxtx, old_signal, signal):
210         # The start bit is always 0 (low). As the idle UART (and the stop bit)
211         # level is 1 (high), the beginning of a start bit is a falling edge.
212         if not (old_signal == 1 and signal == 0):
213             return
214
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         # Skip samples until we're in the middle of the start bit.
222         if not self.reached_bit(rxtx, 0):
223             return
224
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.state[rxtx] = 'WAIT FOR START BIT'
233             return
234
235         self.cur_data_bit[rxtx] = 0
236         self.datavalue[rxtx] = 0
237         self.startsample[rxtx] = -1
238
239         self.state[rxtx] = 'GET DATA BITS'
240
241         self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
242         self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
243
244     def get_data_bits(self, rxtx, signal):
245         # Skip samples until we're in the middle of the desired data bit.
246         if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
247             return
248
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         # Get the next data bit in LSB-first or MSB-first fashion.
254         if self.options['bit_order'] == 'lsb-first':
255             self.datavalue[rxtx] >>= 1
256             self.datavalue[rxtx] |= \
257                 (signal << (self.options['num_data_bits'] - 1))
258         else:
259             self.datavalue[rxtx] <<= 1
260             self.datavalue[rxtx] |= (signal << 0)
261
262         self.putg([rxtx + 12, ['%d' % signal]])
263
264         # Store individual data bits and their start/end samplenumbers.
265         s, halfbit = self.samplenum, int(self.bit_width / 2)
266         self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
267
268         # Return here, unless we already received all data bits.
269         if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
270             self.cur_data_bit[rxtx] += 1
271             return
272
273         self.state[rxtx] = 'GET PARITY BIT'
274
275         self.putpx(rxtx, ['DATA', rxtx,
276             (self.datavalue[rxtx], self.databits[rxtx])])
277
278         b = self.datavalue[rxtx]
279         formatted = self.format_value(b)
280         if formatted is not None:
281             self.putx(rxtx, [rxtx, [formatted]])
282
283         bdata = b.to_bytes(self.bw, byteorder='big')
284         self.putbin(rxtx, [rxtx, bdata])
285         self.putbin(rxtx, [2, bdata])
286
287         self.databits[rxtx] = []
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         # If no parity is used/configured, skip to the next state immediately.
333         if self.options['parity_type'] == 'none':
334             self.state[rxtx] = 'GET STOP BITS'
335             return
336
337         # Skip samples until we're in the middle of the parity bit.
338         if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
339             return
340
341         self.paritybit[rxtx] = signal
342
343         self.state[rxtx] = 'GET STOP BITS'
344
345         if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
346                      self.datavalue[rxtx], self.options['num_data_bits']):
347             self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
348             self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
349         else:
350             # TODO: Return expected/actual parity values.
351             self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
352             self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
353
354     # TODO: Currently only supports 1 stop bit.
355     def get_stop_bits(self, rxtx, signal):
356         # Skip samples until we're in the middle of the stop bit(s).
357         skip_parity = 0 if self.options['parity_type'] == 'none' else 1
358         b = self.options['num_data_bits'] + 1 + skip_parity
359         if not self.reached_bit(rxtx, b):
360             return
361
362         self.stopbit1[rxtx] = signal
363
364         # Stop bits must be 1. If not, we report an error.
365         if self.stopbit1[rxtx] != 1:
366             self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
367             self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
368             # TODO: Abort? Ignore the frame? Other?
369
370         self.state[rxtx] = 'WAIT FOR START BIT'
371
372         self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
373         self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
374
375     def decode(self, ss, es, data):
376         if not self.samplerate:
377             raise SamplerateError('Cannot decode without samplerate.')
378         for (self.samplenum, pins) in data:
379
380             # We want to skip identical samples for performance reasons but,
381             # for now, we can only do that when we are in the idle state
382             # (meaning both channels are waiting for the start bit).
383             if self.state == self.idle_state and self.oldpins == pins:
384                 continue
385
386             self.oldpins, (rx, tx) = pins, pins
387
388             if self.options['invert_rx'] == 'yes':
389                 rx = not rx
390             if self.options['invert_tx'] == 'yes':
391                 tx = not tx
392
393             # Either RX or TX (but not both) can be omitted.
394             has_pin = [rx in (0, 1), tx in (0, 1)]
395             if has_pin == [False, False]:
396                 raise ChannelError('Either TX or RX (or both) pins required.')
397
398             # State machine.
399             for rxtx in (RX, TX):
400                 # Don't try to handle RX (or TX) if not supplied.
401                 if not has_pin[rxtx]:
402                     continue
403
404                 signal = rx if (rxtx == RX) else tx
405
406                 if self.state[rxtx] == 'WAIT FOR START BIT':
407                     self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
408                 elif self.state[rxtx] == 'GET START BIT':
409                     self.get_start_bit(rxtx, signal)
410                 elif self.state[rxtx] == 'GET DATA BITS':
411                     self.get_data_bits(rxtx, signal)
412                 elif self.state[rxtx] == 'GET PARITY BIT':
413                     self.get_parity_bit(rxtx, signal)
414                 elif self.state[rxtx] == 'GET STOP BITS':
415                     self.get_stop_bits(rxtx, signal)
416
417                 # Save current RX/TX values for the next round.
418                 self.oldbit[rxtx] = signal