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