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