]> sigrok.org Git - libsigrokdecode.git/blame_incremental - decoders/uart/pd.py
spi: Tell stacked decoders about missing CS# signal.
[libsigrokdecode.git] / decoders / uart / pd.py
... / ...
CommitLineData
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
21import sigrokdecode as srd
22
23'''
24OUTPUT_PYTHON format:
25
26Packet:
27[<ptype>, <rxtx>, <pdata>]
28
29This is the list of <ptype>s and their respective <pdata> values:
30 - 'STARTBIT': The data is the (integer) value of the start bit (0/1).
31 - 'DATA': This is always a tuple containing two items:
32 - 1st item: the (integer) value of the UART data. Valid values
33 range from 0 to 512 (as the data can be up to 9 bits in size).
34 - 2nd item: the list of individual data bits and their ss/es numbers.
35 - 'PARITYBIT': The data is the (integer) value of the parity bit (0/1).
36 - 'STOPBIT': The data is the (integer) value of the stop bit (0 or 1).
37 - 'INVALID STARTBIT': The data is the (integer) value of the start bit (0/1).
38 - 'INVALID STOPBIT': The data is the (integer) value of the stop bit (0/1).
39 - 'PARITY ERROR': The data is a tuple with two entries. The first one is
40 the expected parity value, the second is the actual parity value.
41 - TODO: Frame error?
42
43The <rxtx> field is 0 for RX packets, 1 for TX packets.
44'''
45
46# Used for differentiating between the two data directions.
47RX = 0
48TX = 1
49
50# Given a parity type to check (odd, even, zero, one), the value of the
51# parity bit, the value of the data, and the length of the data (5-9 bits,
52# usually 8 bits) return True if the parity is correct, False otherwise.
53# 'none' is _not_ allowed as value for 'parity_type'.
54def parity_ok(parity_type, parity_bit, data, num_data_bits):
55
56 # Handle easy cases first (parity bit is always 1 or 0).
57 if parity_type == 'zero':
58 return parity_bit == 0
59 elif parity_type == 'one':
60 return parity_bit == 1
61
62 # Count number of 1 (high) bits in the data (and the parity bit itself!).
63 ones = bin(data).count('1') + parity_bit
64
65 # Check for odd/even parity.
66 if parity_type == 'odd':
67 return (ones % 2) == 1
68 elif parity_type == 'even':
69 return (ones % 2) == 0
70
71class SamplerateError(Exception):
72 pass
73
74class ChannelError(Exception):
75 pass
76
77class Decoder(srd.Decoder):
78 api_version = 2
79 id = 'uart'
80 name = 'UART'
81 longname = 'Universal Asynchronous Receiver/Transmitter'
82 desc = 'Asynchronous, serial bus.'
83 license = 'gplv2+'
84 inputs = ['logic']
85 outputs = ['uart']
86 optional_channels = (
87 # Allow specifying only one of the signals, e.g. if only one data
88 # direction exists (or is relevant).
89 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
90 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
91 )
92 options = (
93 {'id': 'baudrate', 'desc': 'Baud rate', 'default': 115200},
94 {'id': 'num_data_bits', 'desc': 'Data bits', 'default': 8,
95 'values': (5, 6, 7, 8, 9)},
96 {'id': 'parity_type', 'desc': 'Parity type', 'default': 'none',
97 'values': ('none', 'odd', 'even', 'zero', 'one')},
98 {'id': 'parity_check', 'desc': 'Check parity?', 'default': 'yes',
99 'values': ('yes', 'no')},
100 {'id': 'num_stop_bits', 'desc': 'Stop bits', 'default': 1.0,
101 'values': (0.0, 0.5, 1.0, 1.5)},
102 {'id': 'bit_order', 'desc': 'Bit order', 'default': 'lsb-first',
103 'values': ('lsb-first', 'msb-first')},
104 {'id': 'format', 'desc': 'Data format', 'default': 'ascii',
105 'values': ('ascii', 'dec', 'hex', 'oct', 'bin')},
106 {'id': 'invert_rx', 'desc': 'Invert RX?', 'default': 'no',
107 'values': ('yes', 'no')},
108 {'id': 'invert_tx', 'desc': 'Invert TX?', 'default': 'no',
109 'values': ('yes', 'no')},
110 )
111 annotations = (
112 ('rx-data', 'RX data'),
113 ('tx-data', 'TX data'),
114 ('rx-start', 'RX start bits'),
115 ('tx-start', 'TX start bits'),
116 ('rx-parity-ok', 'RX parity OK bits'),
117 ('tx-parity-ok', 'TX parity OK bits'),
118 ('rx-parity-err', 'RX parity error bits'),
119 ('tx-parity-err', 'TX parity error bits'),
120 ('rx-stop', 'RX stop bits'),
121 ('tx-stop', 'TX stop bits'),
122 ('rx-warnings', 'RX warnings'),
123 ('tx-warnings', 'TX warnings'),
124 ('rx-data-bits', 'RX data bits'),
125 ('tx-data-bits', 'TX data bits'),
126 )
127 annotation_rows = (
128 ('rx-data', 'RX', (0, 2, 4, 6, 8)),
129 ('rx-data-bits', 'RX bits', (12,)),
130 ('rx-warnings', 'RX warnings', (10,)),
131 ('tx-data', 'TX', (1, 3, 5, 7, 9)),
132 ('tx-data-bits', 'TX bits', (13,)),
133 ('tx-warnings', 'TX warnings', (11,)),
134 )
135 binary = (
136 ('rx', 'RX dump'),
137 ('tx', 'TX dump'),
138 ('rxtx', 'RX/TX dump'),
139 )
140
141 def putx(self, rxtx, data):
142 s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
143 self.put(s - halfbit, self.samplenum + halfbit, self.out_ann, data)
144
145 def putpx(self, rxtx, data):
146 s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
147 self.put(s - halfbit, self.samplenum + halfbit, self.out_python, data)
148
149 def putg(self, data):
150 s, halfbit = self.samplenum, int(self.bit_width / 2)
151 self.put(s - halfbit, s + halfbit, self.out_ann, data)
152
153 def putp(self, data):
154 s, halfbit = self.samplenum, int(self.bit_width / 2)
155 self.put(s - halfbit, s + halfbit, self.out_python, data)
156
157 def putbin(self, rxtx, data):
158 s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
159 self.put(s - halfbit, self.samplenum + halfbit, self.out_bin, data)
160
161 def __init__(self, **kwargs):
162 self.samplerate = None
163 self.samplenum = 0
164 self.frame_start = [-1, -1]
165 self.startbit = [-1, -1]
166 self.cur_data_bit = [0, 0]
167 self.databyte = [0, 0]
168 self.paritybit = [-1, -1]
169 self.stopbit1 = [-1, -1]
170 self.startsample = [-1, -1]
171 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
172 self.oldbit = [1, 1]
173 self.oldpins = [1, 1]
174 self.databits = [[], []]
175
176 def start(self):
177 self.out_python = self.register(srd.OUTPUT_PYTHON)
178 self.out_bin = self.register(srd.OUTPUT_BINARY)
179 self.out_ann = self.register(srd.OUTPUT_ANN)
180
181 def metadata(self, key, value):
182 if key == srd.SRD_CONF_SAMPLERATE:
183 self.samplerate = value
184 # The width of one UART bit in number of samples.
185 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
186
187 # Return true if we reached the middle of the desired bit, false otherwise.
188 def reached_bit(self, rxtx, bitnum):
189 # bitpos is the samplenumber which is in the middle of the
190 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
191 # (if used) or the first stop bit, and so on).
192 bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
193 bitpos += bitnum * self.bit_width
194 if self.samplenum >= bitpos:
195 return True
196 return False
197
198 def reached_bit_last(self, rxtx, bitnum):
199 bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
200 if self.samplenum >= bitpos:
201 return True
202 return False
203
204 def wait_for_start_bit(self, rxtx, old_signal, signal):
205 # The start bit is always 0 (low). As the idle UART (and the stop bit)
206 # level is 1 (high), the beginning of a start bit is a falling edge.
207 if not (old_signal == 1 and signal == 0):
208 return
209
210 # Save the sample number where the start bit begins.
211 self.frame_start[rxtx] = self.samplenum
212
213 self.state[rxtx] = 'GET START BIT'
214
215 def get_start_bit(self, rxtx, signal):
216 # Skip samples until we're in the middle of the start bit.
217 if not self.reached_bit(rxtx, 0):
218 return
219
220 self.startbit[rxtx] = signal
221
222 # The startbit must be 0. If not, we report an error.
223 if self.startbit[rxtx] != 0:
224 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
225 # TODO: Abort? Ignore rest of the frame?
226
227 self.cur_data_bit[rxtx] = 0
228 self.databyte[rxtx] = 0
229 self.startsample[rxtx] = -1
230
231 self.state[rxtx] = 'GET DATA BITS'
232
233 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
234 self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
235
236 def get_data_bits(self, rxtx, signal):
237 # Skip samples until we're in the middle of the desired data bit.
238 if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
239 return
240
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 # Get the next data bit in LSB-first or MSB-first fashion.
246 if self.options['bit_order'] == 'lsb-first':
247 self.databyte[rxtx] >>= 1
248 self.databyte[rxtx] |= \
249 (signal << (self.options['num_data_bits'] - 1))
250 else:
251 self.databyte[rxtx] <<= 1
252 self.databyte[rxtx] |= (signal << 0)
253
254 self.putg([rxtx + 12, ['%d' % signal]])
255
256 # Store individual data bits and their start/end samplenumbers.
257 s, halfbit = self.samplenum, int(self.bit_width / 2)
258 self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
259
260 # Return here, unless we already received all data bits.
261 if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
262 self.cur_data_bit[rxtx] += 1
263 return
264
265 self.state[rxtx] = 'GET PARITY BIT'
266
267 self.putpx(rxtx, ['DATA', rxtx,
268 (self.databyte[rxtx], self.databits[rxtx])])
269
270 b, f = self.databyte[rxtx], self.options['format']
271 if f == 'ascii':
272 c = chr(b) if b in range(30, 126 + 1) else '[%02X]' % b
273 self.putx(rxtx, [rxtx, [c]])
274 elif f == 'dec':
275 self.putx(rxtx, [rxtx, [str(b)]])
276 elif f == 'hex':
277 self.putx(rxtx, [rxtx, [hex(b)[2:].zfill(2).upper()]])
278 elif f == 'oct':
279 self.putx(rxtx, [rxtx, [oct(b)[2:].zfill(3)]])
280 elif f == 'bin':
281 self.putx(rxtx, [rxtx, [bin(b)[2:].zfill(8)]])
282
283 self.putbin(rxtx, (rxtx, bytes([b])))
284 self.putbin(rxtx, (2, bytes([b])))
285
286 self.databits = [[], []]
287
288 def get_parity_bit(self, rxtx, signal):
289 # If no parity is used/configured, skip to the next state immediately.
290 if self.options['parity_type'] == 'none':
291 self.state[rxtx] = 'GET STOP BITS'
292 return
293
294 # Skip samples until we're in the middle of the parity bit.
295 if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
296 return
297
298 self.paritybit[rxtx] = signal
299
300 self.state[rxtx] = 'GET STOP BITS'
301
302 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
303 self.databyte[rxtx], self.options['num_data_bits']):
304 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
305 self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
306 else:
307 # TODO: Return expected/actual parity values.
308 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
309 self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
310
311 # TODO: Currently only supports 1 stop bit.
312 def get_stop_bits(self, rxtx, signal):
313 # Skip samples until we're in the middle of the stop bit(s).
314 skip_parity = 0 if self.options['parity_type'] == 'none' else 1
315 b = self.options['num_data_bits'] + 1 + skip_parity
316 if not self.reached_bit(rxtx, b):
317 return
318
319 self.stopbit1[rxtx] = signal
320
321 # Stop bits must be 1. If not, we report an error.
322 if self.stopbit1[rxtx] != 1:
323 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
324 self.putg([rxtx + 8, ['Frame error', 'Frame err', 'FE']])
325 # TODO: Abort? Ignore the frame? Other?
326
327 self.state[rxtx] = 'WAIT FOR START BIT'
328
329 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
330 self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
331
332 def decode(self, ss, es, data):
333 if not self.samplerate:
334 raise SamplerateError('Cannot decode without samplerate.')
335 for (self.samplenum, pins) in data:
336
337 # Note: Ignoring identical samples here for performance reasons
338 # is not possible for this PD, at least not in the current state.
339 # if self.oldpins == pins:
340 # continue
341 self.oldpins, (rx, tx) = pins, pins
342
343 if self.options['invert_rx'] == 'yes':
344 rx = not rx
345 if self.options['invert_tx'] == 'yes':
346 tx = not tx
347
348 # Either RX or TX (but not both) can be omitted.
349 has_pin = [rx in (0, 1), tx in (0, 1)]
350 if has_pin == [False, False]:
351 raise ChannelError('Either TX or RX (or both) pins required.')
352
353 # State machine.
354 for rxtx in (RX, TX):
355 # Don't try to handle RX (or TX) if not supplied.
356 if not has_pin[rxtx]:
357 continue
358
359 signal = rx if (rxtx == RX) else tx
360
361 if self.state[rxtx] == 'WAIT FOR START BIT':
362 self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
363 elif self.state[rxtx] == 'GET START BIT':
364 self.get_start_bit(rxtx, signal)
365 elif self.state[rxtx] == 'GET DATA BITS':
366 self.get_data_bits(rxtx, signal)
367 elif self.state[rxtx] == 'GET PARITY BIT':
368 self.get_parity_bit(rxtx, signal)
369 elif self.state[rxtx] == 'GET STOP BITS':
370 self.get_stop_bits(rxtx, signal)
371
372 # Save current RX/TX values for the next round.
373 self.oldbit[rxtx] = signal