]> sigrok.org Git - libsigrokdecode.git/blob - decoders/uart/pd.py
uart: Fix corner-case that can occur with LA triggers.
[libsigrokdecode.git] / decoders / uart / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2011-2013 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 # UART protocol decoder
22
23 import sigrokdecode as srd
24
25 # Used for differentiating between the two data directions.
26 RX = 0
27 TX = 1
28
29 # Annotation feed formats
30 ANN_ASCII = 0
31 ANN_DEC = 1
32 ANN_HEX = 2
33 ANN_OCT = 3
34 ANN_BITS = 4
35
36 # Given a parity type to check (odd, even, zero, one), the value of the
37 # parity bit, the value of the data, and the length of the data (5-9 bits,
38 # usually 8 bits) return True if the parity is correct, False otherwise.
39 # 'none' is _not_ allowed as value for 'parity_type'.
40 def parity_ok(parity_type, parity_bit, data, num_data_bits):
41
42     # Handle easy cases first (parity bit is always 1 or 0).
43     if parity_type == 'zero':
44         return parity_bit == 0
45     elif parity_type == 'one':
46         return parity_bit == 1
47
48     # Count number of 1 (high) bits in the data (and the parity bit itself!).
49     ones = bin(data).count('1') + parity_bit
50
51     # Check for odd/even parity.
52     if parity_type == 'odd':
53         return (ones % 2) == 1
54     elif parity_type == 'even':
55         return (ones % 2) == 0
56     else:
57         raise Exception('Invalid parity type: %d' % parity_type)
58
59 class Decoder(srd.Decoder):
60     api_version = 1
61     id = 'uart'
62     name = 'UART'
63     longname = 'Universal Asynchronous Receiver/Transmitter'
64     desc = 'Asynchronous, serial bus.'
65     license = 'gplv2+'
66     inputs = ['logic']
67     outputs = ['uart']
68     probes = [
69         # Allow specifying only one of the signals, e.g. if only one data
70         # direction exists (or is relevant).
71         {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
72         {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
73     ]
74     optional_probes = []
75     options = {
76         'baudrate': ['Baud rate', 115200],
77         'num_data_bits': ['Data bits', 8], # Valid: 5-9.
78         'parity_type': ['Parity type', 'none'],
79         'parity_check': ['Check parity?', 'yes'], # TODO: Bool supported?
80         'num_stop_bits': ['Stop bit(s)', '1'], # String! 0, 0.5, 1, 1.5.
81         'bit_order': ['Bit order', 'lsb-first'],
82         # TODO: Options to invert the signal(s).
83     }
84     annotations = [
85         ['ASCII', 'Data bytes as ASCII characters'],
86         ['Decimal', 'Databytes as decimal, integer values'],
87         ['Hex', 'Data bytes in hex format'],
88         ['Octal', 'Data bytes as octal numbers'],
89         ['Bits', 'Data bytes in bit notation (sequence of 0/1 digits)'],
90     ]
91
92     def putx(self, rxtx, data):
93         s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
94         self.put(s - halfbit, self.samplenum + halfbit, self.out_ann, data)
95
96     def putg(self, data):
97         s, halfbit = self.samplenum, int(self.bit_width / 2)
98         self.put(s - halfbit, s + halfbit, self.out_ann, data)
99
100     def putp(self, data):
101         s, halfbit = self.samplenum, int(self.bit_width / 2)
102         self.put(s - halfbit, s + halfbit, self.out_proto, data)
103
104     def __init__(self, **kwargs):
105         self.samplenum = 0
106         self.frame_start = [-1, -1]
107         self.startbit = [-1, -1]
108         self.cur_data_bit = [0, 0]
109         self.databyte = [0, 0]
110         self.paritybit = [-1, -1]
111         self.stopbit1 = [-1, -1]
112         self.startsample = [-1, -1]
113         self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
114         self.oldbit = [1, 1]
115         self.oldpins = [1, 1]
116
117     def start(self, metadata):
118         self.samplerate = metadata['samplerate']
119         self.out_proto = self.add(srd.OUTPUT_PROTO, 'uart')
120         self.out_ann = self.add(srd.OUTPUT_ANN, 'uart')
121
122         # The width of one UART bit in number of samples.
123         self.bit_width = \
124             float(self.samplerate) / float(self.options['baudrate'])
125
126     def report(self):
127         pass
128
129     # Return true if we reached the middle of the desired bit, false otherwise.
130     def reached_bit(self, rxtx, bitnum):
131         # bitpos is the samplenumber which is in the middle of the
132         # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
133         # (if used) or the first stop bit, and so on).
134         bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
135         bitpos += bitnum * self.bit_width
136         if self.samplenum >= bitpos:
137             return True
138         return False
139
140     def reached_bit_last(self, rxtx, bitnum):
141         bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
142         if self.samplenum >= bitpos:
143             return True
144         return False
145
146     def wait_for_start_bit(self, rxtx, old_signal, signal):
147         # The start bit is always 0 (low). As the idle UART (and the stop bit)
148         # level is 1 (high), the beginning of a start bit is a falling edge.
149         if not (old_signal == 1 and signal == 0):
150             return
151
152         # Save the sample number where the start bit begins.
153         self.frame_start[rxtx] = self.samplenum
154
155         self.state[rxtx] = 'GET START BIT'
156
157     def get_start_bit(self, rxtx, signal):
158         # Skip samples until we're in the middle of the start bit.
159         if not self.reached_bit(rxtx, 0):
160             return
161
162         self.startbit[rxtx] = signal
163
164         # The startbit must be 0. If not, we report an error.
165         if self.startbit[rxtx] != 0:
166             self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
167             # TODO: Abort? Ignore rest of the frame?
168
169         self.cur_data_bit[rxtx] = 0
170         self.databyte[rxtx] = 0
171         self.startsample[rxtx] = -1
172
173         self.state[rxtx] = 'GET DATA BITS'
174
175         self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
176         self.putg([ANN_ASCII, ['Start bit', 'Start', 'S']])
177
178     def get_data_bits(self, rxtx, signal):
179         # Skip samples until we're in the middle of the desired data bit.
180         if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
181             return
182
183         # Save the sample number of the middle of the first data bit.
184         if self.startsample[rxtx] == -1:
185             self.startsample[rxtx] = self.samplenum
186
187         # Get the next data bit in LSB-first or MSB-first fashion.
188         if self.options['bit_order'] == 'lsb-first':
189             self.databyte[rxtx] >>= 1
190             self.databyte[rxtx] |= \
191                 (signal << (self.options['num_data_bits'] - 1))
192         elif self.options['bit_order'] == 'msb-first':
193             self.databyte[rxtx] <<= 1
194             self.databyte[rxtx] |= (signal << 0)
195         else:
196             raise Exception('Invalid bit order value: %s',
197                             self.options['bit_order'])
198
199         # Return here, unless we already received all data bits.
200         if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
201             self.cur_data_bit[rxtx] += 1
202             return
203
204         self.state[rxtx] = 'GET PARITY BIT'
205
206         self.putp(['DATA', rxtx, self.databyte[rxtx]])
207
208         s = 'RX: ' if (rxtx == RX) else 'TX: '
209         self.putx(rxtx, [ANN_ASCII, [s + chr(self.databyte[rxtx])]])
210         self.putx(rxtx, [ANN_DEC,   [s + str(self.databyte[rxtx])]])
211         self.putx(rxtx, [ANN_HEX,   [s + hex(self.databyte[rxtx]),
212                                      s + hex(self.databyte[rxtx])[2:]]])
213         self.putx(rxtx, [ANN_OCT,   [s + oct(self.databyte[rxtx]),
214                                      s + oct(self.databyte[rxtx])[2:]]])
215         self.putx(rxtx, [ANN_BITS,  [s + bin(self.databyte[rxtx]),
216                                      s + bin(self.databyte[rxtx])[2:]]])
217
218     def get_parity_bit(self, rxtx, signal):
219         # If no parity is used/configured, skip to the next state immediately.
220         if self.options['parity_type'] == 'none':
221             self.state[rxtx] = 'GET STOP BITS'
222             return
223
224         # Skip samples until we're in the middle of the parity bit.
225         if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
226             return
227
228         self.paritybit[rxtx] = signal
229
230         self.state[rxtx] = 'GET STOP BITS'
231
232         if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
233                      self.databyte[rxtx], self.options['num_data_bits']):
234             self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
235             self.putg([ANN_ASCII, ['Parity bit', 'Parity', 'P']])
236         else:
237             # TODO: Return expected/actual parity values.
238             self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
239             self.putg([ANN_ASCII, ['Parity error', 'Parity err', 'PE']])
240
241     # TODO: Currently only supports 1 stop bit.
242     def get_stop_bits(self, rxtx, signal):
243         # Skip samples until we're in the middle of the stop bit(s).
244         skip_parity = 0 if self.options['parity_type'] == 'none' else 1
245         b = self.options['num_data_bits'] + 1 + skip_parity
246         if not self.reached_bit(rxtx, b):
247             return
248
249         self.stopbit1[rxtx] = signal
250
251         # Stop bits must be 1. If not, we report an error.
252         if self.stopbit1[rxtx] != 1:
253             self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
254             # TODO: Abort? Ignore the frame? Other?
255
256         self.state[rxtx] = 'WAIT FOR START BIT'
257
258         self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
259         self.putg([ANN_ASCII, ['Stop bit', 'Stop', 'P']])
260
261     def decode(self, ss, es, data):
262         # TODO: Either RX or TX could be omitted (optional probe).
263         for (self.samplenum, pins) in data:
264
265             # Note: Ignoring identical samples here for performance reasons
266             # is not possible for this PD, at least not in the current state.
267             # if self.oldpins == pins:
268             #     continue
269             self.oldpins, (rx, tx) = pins, pins
270
271             # State machine.
272             for rxtx in (RX, TX):
273                 signal = rx if (rxtx == RX) else tx
274
275                 if self.state[rxtx] == 'WAIT FOR START BIT':
276                     self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
277                 elif self.state[rxtx] == 'GET START BIT':
278                     self.get_start_bit(rxtx, signal)
279                 elif self.state[rxtx] == 'GET DATA BITS':
280                     self.get_data_bits(rxtx, signal)
281                 elif self.state[rxtx] == 'GET PARITY BIT':
282                     self.get_parity_bit(rxtx, signal)
283                 elif self.state[rxtx] == 'GET STOP BITS':
284                     self.get_stop_bits(rxtx, signal)
285                 else:
286                     raise Exception('Invalid state: %s' % self.state[rxtx])
287
288                 # Save current RX/TX values for the next round.
289                 self.oldbit[rxtx] = signal
290