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