]> sigrok.org Git - libsigrokdecode.git/blame - decoders/uart/pd.py
x2444m: Make each command an extra 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.
42 - TODO: Frame error?
43
44The <rxtx> field is 0 for RX packets, 1 for TX packets.
45'''
46
97cca21f
UH
47# Used for differentiating between the two data directions.
48RX = 0
49TX = 1
50
f44d2db2
UH
51# Given a parity type to check (odd, even, zero, one), the value of the
52# parity bit, the value of the data, and the length of the data (5-9 bits,
53# usually 8 bits) return True if the parity is correct, False otherwise.
a7fc4c34 54# 'none' is _not_ allowed as value for 'parity_type'.
f44d2db2
UH
55def parity_ok(parity_type, parity_bit, data, num_data_bits):
56
57 # Handle easy cases first (parity bit is always 1 or 0).
a7fc4c34 58 if parity_type == 'zero':
f44d2db2 59 return parity_bit == 0
a7fc4c34 60 elif parity_type == 'one':
f44d2db2
UH
61 return parity_bit == 1
62
63 # Count number of 1 (high) bits in the data (and the parity bit itself!).
ac941bf9 64 ones = bin(data).count('1') + parity_bit
f44d2db2
UH
65
66 # Check for odd/even parity.
a7fc4c34 67 if parity_type == 'odd':
ac941bf9 68 return (ones % 2) == 1
a7fc4c34 69 elif parity_type == 'even':
ac941bf9 70 return (ones % 2) == 0
f44d2db2 71
21cda951
UH
72class SamplerateError(Exception):
73 pass
74
f04964c6
UH
75class ChannelError(Exception):
76 pass
77
677d597b 78class Decoder(srd.Decoder):
dcd3d626 79 api_version = 3
f44d2db2
UH
80 id = 'uart'
81 name = 'UART'
3d3da57d 82 longname = 'Universal Asynchronous Receiver/Transmitter'
a465436e 83 desc = 'Asynchronous, serial bus.'
f44d2db2
UH
84 license = 'gplv2+'
85 inputs = ['logic']
86 outputs = ['uart']
6a15597a 87 optional_channels = (
f44d2db2
UH
88 # Allow specifying only one of the signals, e.g. if only one data
89 # direction exists (or is relevant).
29ed0f4c
UH
90 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
91 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
da9bcbd9 92 )
84c1c0b5
BV
93 options = (
94 {'id': 'baudrate', 'desc': 'Baud rate', 'default': 115200},
95 {'id': 'num_data_bits', 'desc': 'Data bits', 'default': 8,
96 'values': (5, 6, 7, 8, 9)},
97 {'id': 'parity_type', 'desc': 'Parity type', 'default': 'none',
98 'values': ('none', 'odd', 'even', 'zero', 'one')},
99 {'id': 'parity_check', 'desc': 'Check parity?', 'default': 'yes',
100 'values': ('yes', 'no')},
101 {'id': 'num_stop_bits', 'desc': 'Stop bits', 'default': 1.0,
102 'values': (0.0, 0.5, 1.0, 1.5)},
103 {'id': 'bit_order', 'desc': 'Bit order', 'default': 'lsb-first',
104 'values': ('lsb-first', 'msb-first')},
ea36c198 105 {'id': 'format', 'desc': 'Data format', 'default': 'hex',
84c1c0b5 106 'values': ('ascii', 'dec', 'hex', 'oct', 'bin')},
4eafeeef
DB
107 {'id': 'invert_rx', 'desc': 'Invert RX?', 'default': 'no',
108 'values': ('yes', 'no')},
109 {'id': 'invert_tx', 'desc': 'Invert TX?', 'default': 'no',
110 'values': ('yes', 'no')},
84c1c0b5 111 )
da9bcbd9
BV
112 annotations = (
113 ('rx-data', 'RX data'),
114 ('tx-data', 'TX data'),
115 ('rx-start', 'RX start bits'),
116 ('tx-start', 'TX start bits'),
117 ('rx-parity-ok', 'RX parity OK bits'),
118 ('tx-parity-ok', 'TX parity OK bits'),
119 ('rx-parity-err', 'RX parity error bits'),
120 ('tx-parity-err', 'TX parity error bits'),
121 ('rx-stop', 'RX stop bits'),
122 ('tx-stop', 'TX stop bits'),
123 ('rx-warnings', 'RX warnings'),
124 ('tx-warnings', 'TX warnings'),
125 ('rx-data-bits', 'RX data bits'),
126 ('tx-data-bits', 'TX data bits'),
03a986ea
GS
127 ('rx-break', 'RX break'),
128 ('tx-break', 'TX break'),
da9bcbd9 129 )
2ce20a91 130 annotation_rows = (
4e3b276a 131 ('rx-data', 'RX', (0, 2, 4, 6, 8)),
4aedd5b8 132 ('rx-data-bits', 'RX bits', (12,)),
4e3b276a 133 ('rx-warnings', 'RX warnings', (10,)),
03a986ea 134 ('rx-break', 'RX break', (14,)),
4aedd5b8
UH
135 ('tx-data', 'TX', (1, 3, 5, 7, 9)),
136 ('tx-data-bits', 'TX bits', (13,)),
4e3b276a 137 ('tx-warnings', 'TX warnings', (11,)),
03a986ea 138 ('tx-break', 'TX break', (15,)),
2ce20a91 139 )
0bb7bcf3
UH
140 binary = (
141 ('rx', 'RX dump'),
142 ('tx', 'TX dump'),
143 ('rxtx', 'RX/TX dump'),
144 )
96a044da 145 idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
f44d2db2 146
97cca21f 147 def putx(self, rxtx, data):
b5712ccb
PA
148 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
149 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
15ac6604 150
4aedd5b8 151 def putpx(self, rxtx, data):
b5712ccb
PA
152 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
153 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_python, data)
4aedd5b8 154
15ac6604 155 def putg(self, data):
b5712ccb
PA
156 s, halfbit = self.samplenum, self.bit_width / 2.0
157 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data)
15ac6604
UH
158
159 def putp(self, data):
b5712ccb
PA
160 s, halfbit = self.samplenum, self.bit_width / 2.0
161 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_python, data)
97cca21f 162
03a986ea
GS
163 def putgse(self, ss, es, data):
164 self.put(ss, es, self.out_ann, data)
165
166 def putpse(self, ss, es, data):
167 self.put(ss, es, self.out_python, data)
168
0bb7bcf3 169 def putbin(self, rxtx, data):
b5712ccb 170 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
2f370328 171 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_binary, data)
0bb7bcf3 172
92b7b49f 173 def __init__(self):
10aeb8ea
GS
174 self.reset()
175
176 def reset(self):
f372d597 177 self.samplerate = None
f44d2db2 178 self.samplenum = 0
97cca21f
UH
179 self.frame_start = [-1, -1]
180 self.startbit = [-1, -1]
181 self.cur_data_bit = [0, 0]
e9a3c933 182 self.datavalue = [0, 0]
1ccef461 183 self.paritybit = [-1, -1]
97cca21f
UH
184 self.stopbit1 = [-1, -1]
185 self.startsample = [-1, -1]
2b716038 186 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
4aedd5b8 187 self.databits = [[], []]
03a986ea 188 self.break_start = [None, None]
f44d2db2 189
f372d597 190 def start(self):
c515eed7 191 self.out_python = self.register(srd.OUTPUT_PYTHON)
2f370328 192 self.out_binary = self.register(srd.OUTPUT_BINARY)
be465111 193 self.out_ann = self.register(srd.OUTPUT_ANN)
98b89139 194 self.bw = (self.options['num_data_bits'] + 7) // 8
f44d2db2 195
f372d597
BV
196 def metadata(self, key, value):
197 if key == srd.SRD_CONF_SAMPLERATE:
35b380b1 198 self.samplerate = value
f372d597
BV
199 # The width of one UART bit in number of samples.
200 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
f44d2db2 201
dcd3d626 202 def get_sample_point(self, rxtx, bitnum):
0b83932c 203 # Determine absolute sample number of a bit slot's sample point.
f44d2db2
UH
204 # bitpos is the samplenumber which is in the middle of the
205 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
206 # (if used) or the first stop bit, and so on).
b5712ccb
PA
207 # The samples within bit are 0, 1, ..., (bit_width - 1), therefore
208 # index of the middle sample within bit window is (bit_width - 1) / 2.
209 bitpos = self.frame_start[rxtx] + (self.bit_width - 1) / 2.0
f44d2db2 210 bitpos += bitnum * self.bit_width
dcd3d626
GS
211 return bitpos
212
dcd3d626 213 def wait_for_start_bit(self, rxtx, signal):
f44d2db2 214 # Save the sample number where the start bit begins.
97cca21f 215 self.frame_start[rxtx] = self.samplenum
f44d2db2 216
2b716038 217 self.state[rxtx] = 'GET START BIT'
f44d2db2 218
97cca21f 219 def get_start_bit(self, rxtx, signal):
97cca21f 220 self.startbit[rxtx] = signal
f44d2db2 221
711d0602
GS
222 # The startbit must be 0. If not, we report an error and wait
223 # for the next start bit (assuming this one was spurious).
97cca21f 224 if self.startbit[rxtx] != 0:
15ac6604 225 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
76a4498f 226 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
711d0602
GS
227 self.state[rxtx] = 'WAIT FOR START BIT'
228 return
f44d2db2 229
97cca21f 230 self.cur_data_bit[rxtx] = 0
e9a3c933 231 self.datavalue[rxtx] = 0
97cca21f 232 self.startsample[rxtx] = -1
f44d2db2 233
15ac6604 234 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
2ce20a91 235 self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
f44d2db2 236
4bb42a91
GS
237 self.state[rxtx] = 'GET DATA BITS'
238
97cca21f 239 def get_data_bits(self, rxtx, signal):
15ac6604 240 # Save the sample number of the middle of the first data bit.
97cca21f
UH
241 if self.startsample[rxtx] == -1:
242 self.startsample[rxtx] = self.samplenum
f44d2db2 243
4aedd5b8
UH
244 self.putg([rxtx + 12, ['%d' % signal]])
245
246 # Store individual data bits and their start/end samplenumbers.
247 s, halfbit = self.samplenum, int(self.bit_width / 2)
248 self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
249
f44d2db2 250 # Return here, unless we already received all data bits.
5e3c79fd
GS
251 self.cur_data_bit[rxtx] += 1
252 if self.cur_data_bit[rxtx] < self.options['num_data_bits']:
1bb57ab8 253 return
f44d2db2 254
5166b031
GS
255 # Convert accumulated data bits to a data value.
256 bits = [b[0] for b in self.databits[rxtx]]
257 if self.options['bit_order'] == 'msb-first':
258 bits.reverse()
259 self.datavalue[rxtx] = bitpack(bits)
7cf698c5 260 self.putpx(rxtx, ['DATA', rxtx,
e9a3c933 261 (self.datavalue[rxtx], self.databits[rxtx])])
f44d2db2 262
6ffd71c1
GS
263 b = self.datavalue[rxtx]
264 formatted = self.format_value(b)
265 if formatted is not None:
266 self.putx(rxtx, [rxtx, [formatted]])
f44d2db2 267
98b89139
UH
268 bdata = b.to_bytes(self.bw, byteorder='big')
269 self.putbin(rxtx, [rxtx, bdata])
270 self.putbin(rxtx, [2, bdata])
0bb7bcf3 271
c1fc50b1 272 self.databits[rxtx] = []
4aedd5b8 273
4bb42a91
GS
274 # Advance to either reception of the parity bit, or reception of
275 # the STOP bits if parity is not applicable.
276 self.state[rxtx] = 'GET PARITY BIT'
277 if self.options['parity_type'] == 'none':
278 self.state[rxtx] = 'GET STOP BITS'
279
6ffd71c1
GS
280 def format_value(self, v):
281 # Format value 'v' according to configured options.
282 # Reflects the user selected kind of representation, as well as
283 # the number of data bits in the UART frames.
284
285 fmt, bits = self.options['format'], self.options['num_data_bits']
286
287 # Assume "is printable" for values from 32 to including 126,
288 # below 32 is "control" and thus not printable, above 127 is
289 # "not ASCII" in its strict sense, 127 (DEL) is not printable,
290 # fall back to hex representation for non-printables.
291 if fmt == 'ascii':
292 if v in range(32, 126 + 1):
293 return chr(v)
294 hexfmt = "[{:02X}]" if bits <= 8 else "[{:03X}]"
295 return hexfmt.format(v)
296
297 # Mere number to text conversion without prefix and padding
298 # for the "decimal" output format.
299 if fmt == 'dec':
300 return "{:d}".format(v)
301
302 # Padding with leading zeroes for hex/oct/bin formats, but
303 # without a prefix for density -- since the format is user
304 # specified, there is no ambiguity.
305 if fmt == 'hex':
306 digits = (bits + 4 - 1) // 4
307 fmtchar = "X"
308 elif fmt == 'oct':
309 digits = (bits + 3 - 1) // 3
310 fmtchar = "o"
311 elif fmt == 'bin':
312 digits = bits
313 fmtchar = "b"
314 else:
315 fmtchar = None
316 if fmtchar is not None:
317 fmt = "{{:0{:d}{:s}}}".format(digits, fmtchar)
318 return fmt.format(v)
319
320 return None
321
97cca21f 322 def get_parity_bit(self, rxtx, signal):
97cca21f 323 self.paritybit[rxtx] = signal
f44d2db2 324
ac941bf9 325 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
e9a3c933 326 self.datavalue[rxtx], self.options['num_data_bits']):
15ac6604 327 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
2ce20a91 328 self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
f44d2db2 329 else:
61132abd 330 # TODO: Return expected/actual parity values.
15ac6604 331 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
4e3b276a 332 self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
f44d2db2 333
4bb42a91
GS
334 self.state[rxtx] = 'GET STOP BITS'
335
f44d2db2 336 # TODO: Currently only supports 1 stop bit.
97cca21f 337 def get_stop_bits(self, rxtx, signal):
97cca21f 338 self.stopbit1[rxtx] = signal
f44d2db2 339
5cc4b6a0 340 # Stop bits must be 1. If not, we report an error.
97cca21f 341 if self.stopbit1[rxtx] != 1:
15ac6604 342 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
76a4498f 343 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
5cc4b6a0 344 # TODO: Abort? Ignore the frame? Other?
f44d2db2 345
15ac6604 346 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
2ce20a91 347 self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
f44d2db2 348
4bb42a91
GS
349 self.state[rxtx] = 'WAIT FOR START BIT'
350
03a986ea
GS
351 def handle_break(self, rxtx):
352 self.putpse(self.frame_start[rxtx], self.samplenum,
353 ['BREAK', rxtx, 0])
354 self.putgse(self.frame_start[rxtx], self.samplenum,
355 [rxtx + 14, ['Break condition', 'Break', 'Brk', 'B']])
356 self.state[rxtx] = 'WAIT FOR START BIT'
357
dcd3d626 358 def get_wait_cond(self, rxtx, inv):
0b83932c
UH
359 # Return condititions that are suitable for Decoder.wait(). Those
360 # conditions either match the falling edge of the START bit, or
361 # the sample point of the next bit time.
dcd3d626
GS
362 state = self.state[rxtx]
363 if state == 'WAIT FOR START BIT':
364 return {rxtx: 'r' if inv else 'f'}
365 if state == 'GET START BIT':
366 bitnum = 0
367 elif state == 'GET DATA BITS':
368 bitnum = 1 + self.cur_data_bit[rxtx]
369 elif state == 'GET PARITY BIT':
370 bitnum = 1 + self.options['num_data_bits']
371 elif state == 'GET STOP BITS':
372 bitnum = 1 + self.options['num_data_bits']
373 bitnum += 0 if self.options['parity_type'] == 'none' else 1
0b83932c
UH
374 want_num = ceil(self.get_sample_point(rxtx, bitnum))
375 return {'skip': want_num - self.samplenum}
dcd3d626 376
0de2810f 377 def inspect_sample(self, rxtx, signal, inv):
0b83932c 378 # Inspect a sample returned by .wait() for the specified UART line.
0de2810f
GS
379 if inv:
380 signal = not signal
381
382 state = self.state[rxtx]
383 if state == 'WAIT FOR START BIT':
384 self.wait_for_start_bit(rxtx, signal)
385 elif state == 'GET START BIT':
386 self.get_start_bit(rxtx, signal)
387 elif state == 'GET DATA BITS':
388 self.get_data_bits(rxtx, signal)
389 elif state == 'GET PARITY BIT':
390 self.get_parity_bit(rxtx, signal)
391 elif state == 'GET STOP BITS':
392 self.get_stop_bits(rxtx, signal)
393
03a986ea
GS
394 def inspect_edge(self, rxtx, signal, inv):
395 # Inspect edges, independently from traffic, to detect break conditions.
396 if inv:
397 signal = not signal
398 if not signal:
399 # Signal went low. Start another interval.
400 self.break_start[rxtx] = self.samplenum
401 return
402 # Signal went high. Was there an extended period with low signal?
403 if self.break_start[rxtx] is None:
404 return
405 diff = self.samplenum - self.break_start[rxtx]
406 if diff >= self.break_min_sample_count:
407 self.handle_break(rxtx)
408 self.break_start[rxtx] = None
409
dcd3d626 410 def decode(self):
21cda951
UH
411 if not self.samplerate:
412 raise SamplerateError('Cannot decode without samplerate.')
2fcd7c22 413
dcd3d626
GS
414 has_pin = [self.has_channel(ch) for ch in (RX, TX)]
415 if has_pin == [False, False]:
416 raise ChannelError('Either TX or RX (or both) pins required.')
417
418 opt = self.options
419 inv = [opt['invert_rx'] == 'yes', opt['invert_tx'] == 'yes']
03a986ea
GS
420 cond_data_idx = [None] * len(has_pin)
421
422 # Determine the number of samples for a complete frame's time span.
423 # A period of low signal (at least) that long is a break condition.
424 frame_samples = 1 # START
425 frame_samples += self.options['num_data_bits']
426 frame_samples += 0 if self.options['parity_type'] == 'none' else 1
427 frame_samples += self.options['num_stop_bits']
428 frame_samples *= self.bit_width
429 self.break_min_sample_count = ceil(frame_samples)
430 cond_edge_idx = [None] * len(has_pin)
dcd3d626
GS
431
432 while True:
433 conds = []
434 if has_pin[RX]:
03a986ea 435 cond_data_idx[RX] = len(conds)
dcd3d626 436 conds.append(self.get_wait_cond(RX, inv[RX]))
03a986ea
GS
437 cond_edge_idx[RX] = len(conds)
438 conds.append({RX: 'e'})
dcd3d626 439 if has_pin[TX]:
03a986ea 440 cond_data_idx[TX] = len(conds)
dcd3d626 441 conds.append(self.get_wait_cond(TX, inv[TX]))
03a986ea
GS
442 cond_edge_idx[TX] = len(conds)
443 conds.append({TX: 'e'})
dcd3d626 444 (rx, tx) = self.wait(conds)
03a986ea 445 if cond_data_idx[RX] is not None and self.matched[cond_data_idx[RX]]:
0de2810f 446 self.inspect_sample(RX, rx, inv[RX])
03a986ea
GS
447 if cond_edge_idx[RX] is not None and self.matched[cond_edge_idx[RX]]:
448 self.inspect_edge(RX, rx, inv[RX])
449 if cond_data_idx[TX] is not None and self.matched[cond_data_idx[TX]]:
0de2810f 450 self.inspect_sample(TX, tx, inv[TX])
03a986ea
GS
451 if cond_edge_idx[TX] is not None and self.matched[cond_edge_idx[TX]]:
452 self.inspect_edge(TX, tx, inv[TX])