]> sigrok.org Git - libsigrokdecode.git/blame - decoders/uart/pd.py
uart: allow arbitrary sample positions for UART bit values (1-99%)
[libsigrokdecode.git] / decoders / uart / pd.py
CommitLineData
f44d2db2 1##
50bd5d25 2## This file is part of the libsigrokdecode project.
f44d2db2 3##
0bb7bcf3 4## Copyright (C) 2011-2014 Uwe Hermann <uwe@hermann-uwe.de>
f44d2db2
UH
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
4539e9ca 17## along with this program; if not, see <http://www.gnu.org/licenses/>.
f44d2db2
UH
18##
19
677d597b 20import sigrokdecode as srd
5166b031 21from common.srdhelper import bitpack
b5712ccb 22from math import floor, ceil
f44d2db2 23
4cace3b8 24'''
c515eed7 25OUTPUT_PYTHON format:
4cace3b8 26
bf69977d
UH
27Packet:
28[<ptype>, <rxtx>, <pdata>]
4cace3b8 29
bf69977d 30This is the list of <ptype>s and their respective <pdata> values:
4cace3b8 31 - 'STARTBIT': The data is the (integer) value of the start bit (0/1).
0c7d5a56
UH
32 - 'DATA': This is always a tuple containing two items:
33 - 1st item: the (integer) value of the UART data. Valid values
6ffd71c1 34 range from 0 to 511 (as the data can be up to 9 bits in size).
0c7d5a56 35 - 2nd item: the list of individual data bits and their ss/es numbers.
4cace3b8
UH
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.
b025eab7 42 - 'BREAK': The data is always 0.
96170710
GS
43 - 'FRAME': The data is always a tuple containing two items: The (integer)
44 value of the UART data, and a boolean which reflects the validity of the
45 UART frame.
77c986b3 46 - 'IDLE': The data is always 0.
4cace3b8
UH
47
48The <rxtx> field is 0 for RX packets, 1 for TX packets.
49'''
50
97cca21f
UH
51# Used for differentiating between the two data directions.
52RX = 0
53TX = 1
54
f44d2db2
UH
55# Given a parity type to check (odd, even, zero, one), the value of the
56# parity bit, the value of the data, and the length of the data (5-9 bits,
57# usually 8 bits) return True if the parity is correct, False otherwise.
a7fc4c34 58# 'none' is _not_ allowed as value for 'parity_type'.
fb7a2f68 59def parity_ok(parity_type, parity_bit, data, data_bits):
f44d2db2 60
5ef0a979
GS
61 if parity_type == 'ignore':
62 return True
63
f44d2db2 64 # Handle easy cases first (parity bit is always 1 or 0).
a7fc4c34 65 if parity_type == 'zero':
f44d2db2 66 return parity_bit == 0
a7fc4c34 67 elif parity_type == 'one':
f44d2db2
UH
68 return parity_bit == 1
69
70 # Count number of 1 (high) bits in the data (and the parity bit itself!).
ac941bf9 71 ones = bin(data).count('1') + parity_bit
f44d2db2
UH
72
73 # Check for odd/even parity.
a7fc4c34 74 if parity_type == 'odd':
ac941bf9 75 return (ones % 2) == 1
a7fc4c34 76 elif parity_type == 'even':
ac941bf9 77 return (ones % 2) == 0
f44d2db2 78
21cda951
UH
79class SamplerateError(Exception):
80 pass
81
f04964c6
UH
82class ChannelError(Exception):
83 pass
84
677d597b 85class Decoder(srd.Decoder):
dcd3d626 86 api_version = 3
f44d2db2
UH
87 id = 'uart'
88 name = 'UART'
3d3da57d 89 longname = 'Universal Asynchronous Receiver/Transmitter'
a465436e 90 desc = 'Asynchronous, serial bus.'
f44d2db2
UH
91 license = 'gplv2+'
92 inputs = ['logic']
93 outputs = ['uart']
d6d8a8a4 94 tags = ['Embedded/industrial']
6a15597a 95 optional_channels = (
f44d2db2
UH
96 # Allow specifying only one of the signals, e.g. if only one data
97 # direction exists (or is relevant).
29ed0f4c
UH
98 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
99 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
da9bcbd9 100 )
84c1c0b5
BV
101 options = (
102 {'id': 'baudrate', 'desc': 'Baud rate', 'default': 115200},
fb7a2f68 103 {'id': 'data_bits', 'desc': 'Data bits', 'default': 8,
84c1c0b5 104 'values': (5, 6, 7, 8, 9)},
fb7a2f68 105 {'id': 'parity', 'desc': 'Parity', 'default': 'none',
5ef0a979 106 'values': ('none', 'odd', 'even', 'zero', 'one', 'ignore')},
fb7a2f68 107 {'id': 'stop_bits', 'desc': 'Stop bits', 'default': 1.0,
84c1c0b5
BV
108 'values': (0.0, 0.5, 1.0, 1.5)},
109 {'id': 'bit_order', 'desc': 'Bit order', 'default': 'lsb-first',
110 'values': ('lsb-first', 'msb-first')},
ea36c198 111 {'id': 'format', 'desc': 'Data format', 'default': 'hex',
84c1c0b5 112 'values': ('ascii', 'dec', 'hex', 'oct', 'bin')},
1d764fd0 113 {'id': 'invert_rx', 'desc': 'Invert RX', 'default': 'no',
4eafeeef 114 'values': ('yes', 'no')},
1d764fd0 115 {'id': 'invert_tx', 'desc': 'Invert TX', 'default': 'no',
4eafeeef 116 'values': ('yes', 'no')},
bd50ceb3 117 {'id': 'sample_point', 'desc': 'Sample point (%)', 'default': 50},
fb7a2f68 118 {'id': 'rx_packet_delim', 'desc': 'RX packet delimiter (decimal)',
ab0522b8 119 'default': -1},
fb7a2f68 120 {'id': 'tx_packet_delim', 'desc': 'TX packet delimiter (decimal)',
ab0522b8 121 'default': -1},
0878d4ba
UH
122 {'id': 'rx_packet_len', 'desc': 'RX packet length', 'default': -1},
123 {'id': 'tx_packet_len', 'desc': 'TX packet length', 'default': -1},
84c1c0b5 124 )
da9bcbd9
BV
125 annotations = (
126 ('rx-data', 'RX data'),
127 ('tx-data', 'TX data'),
128 ('rx-start', 'RX start bits'),
129 ('tx-start', 'TX start bits'),
130 ('rx-parity-ok', 'RX parity OK bits'),
131 ('tx-parity-ok', 'TX parity OK bits'),
132 ('rx-parity-err', 'RX parity error bits'),
133 ('tx-parity-err', 'TX parity error bits'),
134 ('rx-stop', 'RX stop bits'),
135 ('tx-stop', 'TX stop bits'),
136 ('rx-warnings', 'RX warnings'),
137 ('tx-warnings', 'TX warnings'),
138 ('rx-data-bits', 'RX data bits'),
139 ('tx-data-bits', 'TX data bits'),
03a986ea
GS
140 ('rx-break', 'RX break'),
141 ('tx-break', 'TX break'),
ab0522b8
UH
142 ('rx-packet', 'RX packet'),
143 ('tx-packet', 'TX packet'),
da9bcbd9 144 )
2ce20a91 145 annotation_rows = (
4aedd5b8 146 ('rx-data-bits', 'RX bits', (12,)),
9d09d6ed 147 ('rx-data', 'RX', (0, 2, 4, 6, 8)),
4e3b276a 148 ('rx-warnings', 'RX warnings', (10,)),
03a986ea 149 ('rx-break', 'RX break', (14,)),
ab0522b8 150 ('rx-packets', 'RX packets', (16,)),
4aedd5b8 151 ('tx-data-bits', 'TX bits', (13,)),
9d09d6ed 152 ('tx-data', 'TX', (1, 3, 5, 7, 9)),
4e3b276a 153 ('tx-warnings', 'TX warnings', (11,)),
03a986ea 154 ('tx-break', 'TX break', (15,)),
ab0522b8 155 ('tx-packets', 'TX packets', (17,)),
2ce20a91 156 )
0bb7bcf3
UH
157 binary = (
158 ('rx', 'RX dump'),
159 ('tx', 'TX dump'),
160 ('rxtx', 'RX/TX dump'),
161 )
96a044da 162 idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
f44d2db2 163
97cca21f 164 def putx(self, rxtx, data):
b5712ccb
PA
165 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
166 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
15ac6604 167
ab0522b8
UH
168 def putx_packet(self, rxtx, data):
169 s, halfbit = self.ss_packet[rxtx], self.bit_width / 2.0
170 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
171
4aedd5b8 172 def putpx(self, rxtx, data):
b5712ccb
PA
173 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
174 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_python, data)
4aedd5b8 175
15ac6604 176 def putg(self, data):
b5712ccb
PA
177 s, halfbit = self.samplenum, self.bit_width / 2.0
178 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data)
15ac6604
UH
179
180 def putp(self, data):
b5712ccb
PA
181 s, halfbit = self.samplenum, self.bit_width / 2.0
182 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_python, data)
97cca21f 183
03a986ea
GS
184 def putgse(self, ss, es, data):
185 self.put(ss, es, self.out_ann, data)
186
187 def putpse(self, ss, es, data):
188 self.put(ss, es, self.out_python, data)
189
0bb7bcf3 190 def putbin(self, rxtx, data):
b5712ccb 191 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
2f370328 192 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_binary, data)
0bb7bcf3 193
92b7b49f 194 def __init__(self):
10aeb8ea
GS
195 self.reset()
196
197 def reset(self):
f372d597 198 self.samplerate = None
97cca21f 199 self.frame_start = [-1, -1]
96170710 200 self.frame_valid = [None, None]
97cca21f
UH
201 self.startbit = [-1, -1]
202 self.cur_data_bit = [0, 0]
e9a3c933 203 self.datavalue = [0, 0]
1ccef461 204 self.paritybit = [-1, -1]
97cca21f
UH
205 self.stopbit1 = [-1, -1]
206 self.startsample = [-1, -1]
2b716038 207 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
4aedd5b8 208 self.databits = [[], []]
03a986ea 209 self.break_start = [None, None]
ab0522b8
UH
210 self.packet_cache = [[], []]
211 self.ss_packet, self.es_packet = [None, None], [None, None]
d97440cc 212 self.idle_start = [None, None]
f44d2db2 213
f372d597 214 def start(self):
c515eed7 215 self.out_python = self.register(srd.OUTPUT_PYTHON)
2f370328 216 self.out_binary = self.register(srd.OUTPUT_BINARY)
be465111 217 self.out_ann = self.register(srd.OUTPUT_ANN)
fb7a2f68 218 self.bw = (self.options['data_bits'] + 7) // 8
f44d2db2 219
f372d597
BV
220 def metadata(self, key, value):
221 if key == srd.SRD_CONF_SAMPLERATE:
35b380b1 222 self.samplerate = value
f372d597
BV
223 # The width of one UART bit in number of samples.
224 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
f44d2db2 225
dcd3d626 226 def get_sample_point(self, rxtx, bitnum):
0b83932c 227 # Determine absolute sample number of a bit slot's sample point.
bd50ceb3
GS
228 # Counts for UART bits start from 0 (0 = start bit, 1..x = data,
229 # x+1 = parity bit (if used) or the first stop bit, and so on).
230 # Accept a position in the range of 1.99% of the full bit width.
231 # Assume 50% for invalid input specs for backwards compatibility.
232 perc = self.options['sample_point'] or 50
233 if not perc or perc not in range(1, 100):
234 perc = 50
235 bitpos = (self.bit_width - 1) * perc / 100
236 bitpos += self.frame_start[rxtx]
f44d2db2 237 bitpos += bitnum * self.bit_width
dcd3d626
GS
238 return bitpos
239
dcd3d626 240 def wait_for_start_bit(self, rxtx, signal):
f44d2db2 241 # Save the sample number where the start bit begins.
97cca21f 242 self.frame_start[rxtx] = self.samplenum
96170710 243 self.frame_valid[rxtx] = True
f44d2db2 244
2b716038 245 self.state[rxtx] = 'GET START BIT'
f44d2db2 246
97cca21f 247 def get_start_bit(self, rxtx, signal):
97cca21f 248 self.startbit[rxtx] = signal
f44d2db2 249
711d0602
GS
250 # The startbit must be 0. If not, we report an error and wait
251 # for the next start bit (assuming this one was spurious).
97cca21f 252 if self.startbit[rxtx] != 0:
15ac6604 253 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
76a4498f 254 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
96170710
GS
255 self.frame_valid[rxtx] = False
256 es = self.samplenum + ceil(self.bit_width / 2.0)
257 self.putpse(self.frame_start[rxtx], es, ['FRAME', rxtx,
258 (self.datavalue[rxtx], self.frame_valid[rxtx])])
711d0602
GS
259 self.state[rxtx] = 'WAIT FOR START BIT'
260 return
f44d2db2 261
97cca21f 262 self.cur_data_bit[rxtx] = 0
e9a3c933 263 self.datavalue[rxtx] = 0
97cca21f 264 self.startsample[rxtx] = -1
f44d2db2 265
15ac6604 266 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
2ce20a91 267 self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
f44d2db2 268
4bb42a91
GS
269 self.state[rxtx] = 'GET DATA BITS'
270
ab0522b8 271 def handle_packet(self, rxtx):
0878d4ba 272 d = 'rx' if (rxtx == RX) else 'tx'
fb7a2f68 273 delim = self.options[d + '_packet_delim']
0878d4ba
UH
274 plen = self.options[d + '_packet_len']
275 if delim == -1 and plen == -1:
ab0522b8
UH
276 return
277
0878d4ba
UH
278 # Cache data values until we see the delimiter and/or the specified
279 # packet length has been reached (whichever happens first).
ab0522b8
UH
280 if len(self.packet_cache[rxtx]) == 0:
281 self.ss_packet[rxtx] = self.startsample[rxtx]
282 self.packet_cache[rxtx].append(self.datavalue[rxtx])
0878d4ba 283 if self.datavalue[rxtx] == delim or len(self.packet_cache[rxtx]) == plen:
ab0522b8
UH
284 self.es_packet[rxtx] = self.samplenum
285 s = ''
286 for b in self.packet_cache[rxtx]:
287 s += self.format_value(b)
288 if self.options['format'] != 'ascii':
289 s += ' '
290 if self.options['format'] != 'ascii' and s[-1] == ' ':
291 s = s[:-1] # Drop trailing space.
292 self.putx_packet(rxtx, [16 + rxtx, [s]])
293 self.packet_cache[rxtx] = []
294
97cca21f 295 def get_data_bits(self, rxtx, signal):
15ac6604 296 # Save the sample number of the middle of the first data bit.
97cca21f
UH
297 if self.startsample[rxtx] == -1:
298 self.startsample[rxtx] = self.samplenum
f44d2db2 299
4aedd5b8
UH
300 self.putg([rxtx + 12, ['%d' % signal]])
301
302 # Store individual data bits and their start/end samplenumbers.
303 s, halfbit = self.samplenum, int(self.bit_width / 2)
304 self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
305
f44d2db2 306 # Return here, unless we already received all data bits.
5e3c79fd 307 self.cur_data_bit[rxtx] += 1
fb7a2f68 308 if self.cur_data_bit[rxtx] < self.options['data_bits']:
1bb57ab8 309 return
f44d2db2 310
5166b031
GS
311 # Convert accumulated data bits to a data value.
312 bits = [b[0] for b in self.databits[rxtx]]
313 if self.options['bit_order'] == 'msb-first':
314 bits.reverse()
315 self.datavalue[rxtx] = bitpack(bits)
7cf698c5 316 self.putpx(rxtx, ['DATA', rxtx,
e9a3c933 317 (self.datavalue[rxtx], self.databits[rxtx])])
f44d2db2 318
6ffd71c1
GS
319 b = self.datavalue[rxtx]
320 formatted = self.format_value(b)
321 if formatted is not None:
322 self.putx(rxtx, [rxtx, [formatted]])
f44d2db2 323
98b89139
UH
324 bdata = b.to_bytes(self.bw, byteorder='big')
325 self.putbin(rxtx, [rxtx, bdata])
326 self.putbin(rxtx, [2, bdata])
0bb7bcf3 327
ab0522b8
UH
328 self.handle_packet(rxtx)
329
c1fc50b1 330 self.databits[rxtx] = []
4aedd5b8 331
4bb42a91
GS
332 # Advance to either reception of the parity bit, or reception of
333 # the STOP bits if parity is not applicable.
334 self.state[rxtx] = 'GET PARITY BIT'
fb7a2f68 335 if self.options['parity'] == 'none':
4bb42a91
GS
336 self.state[rxtx] = 'GET STOP BITS'
337
6ffd71c1
GS
338 def format_value(self, v):
339 # Format value 'v' according to configured options.
340 # Reflects the user selected kind of representation, as well as
341 # the number of data bits in the UART frames.
342
fb7a2f68 343 fmt, bits = self.options['format'], self.options['data_bits']
6ffd71c1
GS
344
345 # Assume "is printable" for values from 32 to including 126,
346 # below 32 is "control" and thus not printable, above 127 is
347 # "not ASCII" in its strict sense, 127 (DEL) is not printable,
348 # fall back to hex representation for non-printables.
349 if fmt == 'ascii':
350 if v in range(32, 126 + 1):
351 return chr(v)
352 hexfmt = "[{:02X}]" if bits <= 8 else "[{:03X}]"
353 return hexfmt.format(v)
354
355 # Mere number to text conversion without prefix and padding
356 # for the "decimal" output format.
357 if fmt == 'dec':
358 return "{:d}".format(v)
359
360 # Padding with leading zeroes for hex/oct/bin formats, but
361 # without a prefix for density -- since the format is user
362 # specified, there is no ambiguity.
363 if fmt == 'hex':
364 digits = (bits + 4 - 1) // 4
365 fmtchar = "X"
366 elif fmt == 'oct':
367 digits = (bits + 3 - 1) // 3
368 fmtchar = "o"
369 elif fmt == 'bin':
370 digits = bits
371 fmtchar = "b"
372 else:
373 fmtchar = None
374 if fmtchar is not None:
375 fmt = "{{:0{:d}{:s}}}".format(digits, fmtchar)
376 return fmt.format(v)
377
378 return None
379
97cca21f 380 def get_parity_bit(self, rxtx, signal):
97cca21f 381 self.paritybit[rxtx] = signal
f44d2db2 382
fb7a2f68
UH
383 if parity_ok(self.options['parity'], self.paritybit[rxtx],
384 self.datavalue[rxtx], self.options['data_bits']):
15ac6604 385 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
2ce20a91 386 self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
f44d2db2 387 else:
61132abd 388 # TODO: Return expected/actual parity values.
15ac6604 389 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
4e3b276a 390 self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
96170710 391 self.frame_valid[rxtx] = False
f44d2db2 392
4bb42a91
GS
393 self.state[rxtx] = 'GET STOP BITS'
394
f44d2db2 395 # TODO: Currently only supports 1 stop bit.
97cca21f 396 def get_stop_bits(self, rxtx, signal):
97cca21f 397 self.stopbit1[rxtx] = signal
f44d2db2 398
5cc4b6a0 399 # Stop bits must be 1. If not, we report an error.
97cca21f 400 if self.stopbit1[rxtx] != 1:
15ac6604 401 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
76a4498f 402 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
96170710 403 self.frame_valid[rxtx] = False
f44d2db2 404
15ac6604 405 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
2ce20a91 406 self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
f44d2db2 407
96170710
GS
408 # Pass the complete UART frame to upper layers.
409 es = self.samplenum + ceil(self.bit_width / 2.0)
410 self.putpse(self.frame_start[rxtx], es, ['FRAME', rxtx,
411 (self.datavalue[rxtx], self.frame_valid[rxtx])])
412
4bb42a91 413 self.state[rxtx] = 'WAIT FOR START BIT'
d97440cc 414 self.idle_start[rxtx] = self.frame_start[rxtx] + self.frame_len_sample_count
4bb42a91 415
03a986ea
GS
416 def handle_break(self, rxtx):
417 self.putpse(self.frame_start[rxtx], self.samplenum,
418 ['BREAK', rxtx, 0])
419 self.putgse(self.frame_start[rxtx], self.samplenum,
420 [rxtx + 14, ['Break condition', 'Break', 'Brk', 'B']])
421 self.state[rxtx] = 'WAIT FOR START BIT'
422
dcd3d626 423 def get_wait_cond(self, rxtx, inv):
0b83932c
UH
424 # Return condititions that are suitable for Decoder.wait(). Those
425 # conditions either match the falling edge of the START bit, or
426 # the sample point of the next bit time.
dcd3d626
GS
427 state = self.state[rxtx]
428 if state == 'WAIT FOR START BIT':
429 return {rxtx: 'r' if inv else 'f'}
430 if state == 'GET START BIT':
431 bitnum = 0
432 elif state == 'GET DATA BITS':
433 bitnum = 1 + self.cur_data_bit[rxtx]
434 elif state == 'GET PARITY BIT':
fb7a2f68 435 bitnum = 1 + self.options['data_bits']
dcd3d626 436 elif state == 'GET STOP BITS':
fb7a2f68
UH
437 bitnum = 1 + self.options['data_bits']
438 bitnum += 0 if self.options['parity'] == 'none' else 1
0b83932c
UH
439 want_num = ceil(self.get_sample_point(rxtx, bitnum))
440 return {'skip': want_num - self.samplenum}
dcd3d626 441
d97440cc
GS
442 def get_idle_cond(self, rxtx, inv):
443 # Return a condition that corresponds to the (expected) end of
444 # the next frame, assuming that it will be an "idle frame"
445 # (constant high input level for the frame's length).
446 if self.idle_start[rxtx] is None:
447 return None
448 end_of_frame = self.idle_start[rxtx] + self.frame_len_sample_count
449 if end_of_frame < self.samplenum:
450 return None
451 return {'skip': end_of_frame - self.samplenum}
452
0de2810f 453 def inspect_sample(self, rxtx, signal, inv):
0b83932c 454 # Inspect a sample returned by .wait() for the specified UART line.
0de2810f
GS
455 if inv:
456 signal = not signal
457
458 state = self.state[rxtx]
459 if state == 'WAIT FOR START BIT':
460 self.wait_for_start_bit(rxtx, signal)
461 elif state == 'GET START BIT':
462 self.get_start_bit(rxtx, signal)
463 elif state == 'GET DATA BITS':
464 self.get_data_bits(rxtx, signal)
465 elif state == 'GET PARITY BIT':
466 self.get_parity_bit(rxtx, signal)
467 elif state == 'GET STOP BITS':
468 self.get_stop_bits(rxtx, signal)
469
03a986ea
GS
470 def inspect_edge(self, rxtx, signal, inv):
471 # Inspect edges, independently from traffic, to detect break conditions.
472 if inv:
473 signal = not signal
474 if not signal:
475 # Signal went low. Start another interval.
476 self.break_start[rxtx] = self.samplenum
477 return
478 # Signal went high. Was there an extended period with low signal?
479 if self.break_start[rxtx] is None:
480 return
481 diff = self.samplenum - self.break_start[rxtx]
482 if diff >= self.break_min_sample_count:
483 self.handle_break(rxtx)
484 self.break_start[rxtx] = None
485
d97440cc
GS
486 def inspect_idle(self, rxtx, signal, inv):
487 # Check each edge and each period of stable input (either level).
488 # Can derive the "idle frame period has passed" condition.
489 if inv:
490 signal = not signal
491 if not signal:
492 # Low input, cease inspection.
493 self.idle_start[rxtx] = None
494 return
495 # High input, either just reached, or still stable.
496 if self.idle_start[rxtx] is None:
497 self.idle_start[rxtx] = self.samplenum
498 diff = self.samplenum - self.idle_start[rxtx]
499 if diff < self.frame_len_sample_count:
500 return
501 ss, es = self.idle_start[rxtx], self.samplenum
502 self.putpse(ss, es, ['IDLE', rxtx, 0])
503 self.idle_start[rxtx] = self.samplenum
504
dcd3d626 505 def decode(self):
21cda951
UH
506 if not self.samplerate:
507 raise SamplerateError('Cannot decode without samplerate.')
2fcd7c22 508
dcd3d626 509 has_pin = [self.has_channel(ch) for ch in (RX, TX)]
81bb8e84
GS
510 if not True in has_pin:
511 raise ChannelError('Need at least one of TX or RX pins.')
dcd3d626
GS
512
513 opt = self.options
514 inv = [opt['invert_rx'] == 'yes', opt['invert_tx'] == 'yes']
03a986ea
GS
515 cond_data_idx = [None] * len(has_pin)
516
517 # Determine the number of samples for a complete frame's time span.
518 # A period of low signal (at least) that long is a break condition.
519 frame_samples = 1 # START
fb7a2f68
UH
520 frame_samples += self.options['data_bits']
521 frame_samples += 0 if self.options['parity'] == 'none' else 1
522 frame_samples += self.options['stop_bits']
03a986ea 523 frame_samples *= self.bit_width
d97440cc
GS
524 self.frame_len_sample_count = ceil(frame_samples)
525 self.break_min_sample_count = self.frame_len_sample_count
03a986ea 526 cond_edge_idx = [None] * len(has_pin)
d97440cc 527 cond_idle_idx = [None] * len(has_pin)
dcd3d626
GS
528
529 while True:
530 conds = []
531 if has_pin[RX]:
03a986ea 532 cond_data_idx[RX] = len(conds)
dcd3d626 533 conds.append(self.get_wait_cond(RX, inv[RX]))
03a986ea
GS
534 cond_edge_idx[RX] = len(conds)
535 conds.append({RX: 'e'})
d97440cc
GS
536 cond_idle_idx[RX] = None
537 idle_cond = self.get_idle_cond(RX, inv[RX])
538 if idle_cond:
539 cond_idle_idx[RX] = len(conds)
540 conds.append(idle_cond)
dcd3d626 541 if has_pin[TX]:
03a986ea 542 cond_data_idx[TX] = len(conds)
dcd3d626 543 conds.append(self.get_wait_cond(TX, inv[TX]))
03a986ea
GS
544 cond_edge_idx[TX] = len(conds)
545 conds.append({TX: 'e'})
d97440cc
GS
546 cond_idle_idx[TX] = None
547 idle_cond = self.get_idle_cond(TX, inv[TX])
548 if idle_cond:
549 cond_idle_idx[TX] = len(conds)
550 conds.append(idle_cond)
dcd3d626 551 (rx, tx) = self.wait(conds)
03a986ea 552 if cond_data_idx[RX] is not None and self.matched[cond_data_idx[RX]]:
0de2810f 553 self.inspect_sample(RX, rx, inv[RX])
03a986ea
GS
554 if cond_edge_idx[RX] is not None and self.matched[cond_edge_idx[RX]]:
555 self.inspect_edge(RX, rx, inv[RX])
d97440cc
GS
556 self.inspect_idle(RX, rx, inv[RX])
557 if cond_idle_idx[RX] is not None and self.matched[cond_idle_idx[RX]]:
558 self.inspect_idle(RX, rx, inv[RX])
03a986ea 559 if cond_data_idx[TX] is not None and self.matched[cond_data_idx[TX]]:
0de2810f 560 self.inspect_sample(TX, tx, inv[TX])
03a986ea
GS
561 if cond_edge_idx[TX] is not None and self.matched[cond_edge_idx[TX]]:
562 self.inspect_edge(TX, tx, inv[TX])
d97440cc
GS
563 self.inspect_idle(TX, tx, inv[TX])
564 if cond_idle_idx[TX] is not None and self.matched[cond_idle_idx[TX]]:
565 self.inspect_idle(TX, tx, inv[TX])