]> sigrok.org Git - libsigrokdecode.git/blame_incremental - decoders/uart/pd.py
uart: Minor readability nit (position of start bit in calculation)
[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, see <http://www.gnu.org/licenses/>.
18##
19
20import sigrokdecode as srd
21from math import floor, ceil
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 511 (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': 'hex',
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 idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
141
142 def putx(self, rxtx, data):
143 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
144 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
145
146 def putpx(self, rxtx, data):
147 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
148 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_python, data)
149
150 def putg(self, data):
151 s, halfbit = self.samplenum, self.bit_width / 2.0
152 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data)
153
154 def putp(self, data):
155 s, halfbit = self.samplenum, self.bit_width / 2.0
156 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_python, data)
157
158 def putbin(self, rxtx, data):
159 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
160 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_binary, data)
161
162 def __init__(self):
163 self.samplerate = None
164 self.samplenum = 0
165 self.frame_start = [-1, -1]
166 self.startbit = [-1, -1]
167 self.cur_data_bit = [0, 0]
168 self.datavalue = [0, 0]
169 self.paritybit = [-1, -1]
170 self.stopbit1 = [-1, -1]
171 self.startsample = [-1, -1]
172 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
173 self.oldbit = [1, 1]
174 self.oldpins = [-1, -1]
175 self.databits = [[], []]
176
177 def start(self):
178 self.out_python = self.register(srd.OUTPUT_PYTHON)
179 self.out_binary = self.register(srd.OUTPUT_BINARY)
180 self.out_ann = self.register(srd.OUTPUT_ANN)
181 self.bw = (self.options['num_data_bits'] + 7) // 8
182
183 def metadata(self, key, value):
184 if key == srd.SRD_CONF_SAMPLERATE:
185 self.samplerate = value
186 # The width of one UART bit in number of samples.
187 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
188
189 # Return true if we reached the middle of the desired bit, false otherwise.
190 def reached_bit(self, rxtx, bitnum):
191 # bitpos is the samplenumber which is in the middle of the
192 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
193 # (if used) or the first stop bit, and so on).
194 # The samples within bit are 0, 1, ..., (bit_width - 1), therefore
195 # index of the middle sample within bit window is (bit_width - 1) / 2.
196 bitpos = self.frame_start[rxtx] + (self.bit_width - 1) / 2.0
197 bitpos += bitnum * self.bit_width
198 if self.samplenum >= bitpos:
199 return True
200 return False
201
202 def wait_for_start_bit(self, rxtx, old_signal, signal):
203 # The start bit is always 0 (low). As the idle UART (and the stop bit)
204 # level is 1 (high), the beginning of a start bit is a falling edge.
205 if not (old_signal == 1 and signal == 0):
206 return
207
208 # Save the sample number where the start bit begins.
209 self.frame_start[rxtx] = self.samplenum
210
211 self.state[rxtx] = 'GET START BIT'
212
213 def get_start_bit(self, rxtx, signal):
214 # Skip samples until we're in the middle of the start bit.
215 if not self.reached_bit(rxtx, 0):
216 return
217
218 self.startbit[rxtx] = signal
219
220 # The startbit must be 0. If not, we report an error and wait
221 # for the next start bit (assuming this one was spurious).
222 if self.startbit[rxtx] != 0:
223 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
224 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
225 self.state[rxtx] = 'WAIT FOR START BIT'
226 return
227
228 self.cur_data_bit[rxtx] = 0
229 self.datavalue[rxtx] = 0
230 self.startsample[rxtx] = -1
231
232 self.state[rxtx] = 'GET DATA BITS'
233
234 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
235 self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
236
237 def get_data_bits(self, rxtx, signal):
238 # Skip samples until we're in the middle of the desired data bit.
239 if not self.reached_bit(rxtx, 1 + self.cur_data_bit[rxtx]):
240 return
241
242 # Save the sample number of the middle of the first data bit.
243 if self.startsample[rxtx] == -1:
244 self.startsample[rxtx] = self.samplenum
245
246 # Get the next data bit in LSB-first or MSB-first fashion.
247 if self.options['bit_order'] == 'lsb-first':
248 self.datavalue[rxtx] >>= 1
249 self.datavalue[rxtx] |= \
250 (signal << (self.options['num_data_bits'] - 1))
251 else:
252 self.datavalue[rxtx] <<= 1
253 self.datavalue[rxtx] |= (signal << 0)
254
255 self.putg([rxtx + 12, ['%d' % signal]])
256
257 # Store individual data bits and their start/end samplenumbers.
258 s, halfbit = self.samplenum, int(self.bit_width / 2)
259 self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
260
261 # Return here, unless we already received all data bits.
262 self.cur_data_bit[rxtx] += 1
263 if self.cur_data_bit[rxtx] < self.options['num_data_bits']:
264 return
265
266 # Skip to either reception of the parity bit, or reception of
267 # the STOP bits if parity is not applicable.
268 self.state[rxtx] = 'GET PARITY BIT'
269 if self.options['parity_type'] == 'none':
270 self.state[rxtx] = 'GET STOP BITS'
271
272 self.putpx(rxtx, ['DATA', rxtx,
273 (self.datavalue[rxtx], self.databits[rxtx])])
274
275 b = self.datavalue[rxtx]
276 formatted = self.format_value(b)
277 if formatted is not None:
278 self.putx(rxtx, [rxtx, [formatted]])
279
280 bdata = b.to_bytes(self.bw, byteorder='big')
281 self.putbin(rxtx, [rxtx, bdata])
282 self.putbin(rxtx, [2, bdata])
283
284 self.databits[rxtx] = []
285
286 def format_value(self, v):
287 # Format value 'v' according to configured options.
288 # Reflects the user selected kind of representation, as well as
289 # the number of data bits in the UART frames.
290
291 fmt, bits = self.options['format'], self.options['num_data_bits']
292
293 # Assume "is printable" for values from 32 to including 126,
294 # below 32 is "control" and thus not printable, above 127 is
295 # "not ASCII" in its strict sense, 127 (DEL) is not printable,
296 # fall back to hex representation for non-printables.
297 if fmt == 'ascii':
298 if v in range(32, 126 + 1):
299 return chr(v)
300 hexfmt = "[{:02X}]" if bits <= 8 else "[{:03X}]"
301 return hexfmt.format(v)
302
303 # Mere number to text conversion without prefix and padding
304 # for the "decimal" output format.
305 if fmt == 'dec':
306 return "{:d}".format(v)
307
308 # Padding with leading zeroes for hex/oct/bin formats, but
309 # without a prefix for density -- since the format is user
310 # specified, there is no ambiguity.
311 if fmt == 'hex':
312 digits = (bits + 4 - 1) // 4
313 fmtchar = "X"
314 elif fmt == 'oct':
315 digits = (bits + 3 - 1) // 3
316 fmtchar = "o"
317 elif fmt == 'bin':
318 digits = bits
319 fmtchar = "b"
320 else:
321 fmtchar = None
322 if fmtchar is not None:
323 fmt = "{{:0{:d}{:s}}}".format(digits, fmtchar)
324 return fmt.format(v)
325
326 return None
327
328 def get_parity_bit(self, rxtx, signal):
329 # Skip samples until we're in the middle of the parity bit.
330 if not self.reached_bit(rxtx, 1 + self.options['num_data_bits']):
331 return
332
333 self.paritybit[rxtx] = signal
334
335 self.state[rxtx] = 'GET STOP BITS'
336
337 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
338 self.datavalue[rxtx], self.options['num_data_bits']):
339 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
340 self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
341 else:
342 # TODO: Return expected/actual parity values.
343 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
344 self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
345
346 # TODO: Currently only supports 1 stop bit.
347 def get_stop_bits(self, rxtx, signal):
348 # Skip samples until we're in the middle of the stop bit(s).
349 skip_parity = 0 if self.options['parity_type'] == 'none' else 1
350 b = 1 + self.options['num_data_bits'] + skip_parity
351 if not self.reached_bit(rxtx, b):
352 return
353
354 self.stopbit1[rxtx] = signal
355
356 # Stop bits must be 1. If not, we report an error.
357 if self.stopbit1[rxtx] != 1:
358 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
359 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
360 # TODO: Abort? Ignore the frame? Other?
361
362 self.state[rxtx] = 'WAIT FOR START BIT'
363
364 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
365 self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
366
367 def decode(self, ss, es, data):
368 if not self.samplerate:
369 raise SamplerateError('Cannot decode without samplerate.')
370 for (self.samplenum, pins) in data:
371
372 # We want to skip identical samples for performance reasons but,
373 # for now, we can only do that when we are in the idle state
374 # (meaning both channels are waiting for the start bit).
375 if self.state == self.idle_state and self.oldpins == pins:
376 continue
377
378 self.oldpins, (rx, tx) = pins, pins
379
380 if self.options['invert_rx'] == 'yes':
381 rx = not rx
382 if self.options['invert_tx'] == 'yes':
383 tx = not tx
384
385 # Either RX or TX (but not both) can be omitted.
386 has_pin = [rx in (0, 1), tx in (0, 1)]
387 if has_pin == [False, False]:
388 raise ChannelError('Either TX or RX (or both) pins required.')
389
390 # State machine.
391 for rxtx in (RX, TX):
392 # Don't try to handle RX (or TX) if not supplied.
393 if not has_pin[rxtx]:
394 continue
395
396 signal = rx if (rxtx == RX) else tx
397
398 if self.state[rxtx] == 'WAIT FOR START BIT':
399 self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
400 elif self.state[rxtx] == 'GET START BIT':
401 self.get_start_bit(rxtx, signal)
402 elif self.state[rxtx] == 'GET DATA BITS':
403 self.get_data_bits(rxtx, signal)
404 elif self.state[rxtx] == 'GET PARITY BIT':
405 self.get_parity_bit(rxtx, signal)
406 elif self.state[rxtx] == 'GET STOP BITS':
407 self.get_stop_bits(rxtx, signal)
408
409 # Save current RX/TX values for the next round.
410 self.oldbit[rxtx] = signal