]> sigrok.org Git - libsigrokdecode.git/blame - decoders/uart/pd.py
uart: Fix a bug in the output for stacked PDs.
[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
17## along with this program; if not, write to the Free Software
18## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19##
20
677d597b 21import sigrokdecode as srd
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
34 range from 0 to 512 (as the data can be up to 9 bits in size).
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):
12851357 79 api_version = 2
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')},
105 {'id': 'format', 'desc': 'Data format', 'default': 'ascii',
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'),
127 )
2ce20a91 128 annotation_rows = (
4e3b276a 129 ('rx-data', 'RX', (0, 2, 4, 6, 8)),
4aedd5b8 130 ('rx-data-bits', 'RX bits', (12,)),
4e3b276a 131 ('rx-warnings', 'RX warnings', (10,)),
4aedd5b8
UH
132 ('tx-data', 'TX', (1, 3, 5, 7, 9)),
133 ('tx-data-bits', 'TX bits', (13,)),
4e3b276a 134 ('tx-warnings', 'TX warnings', (11,)),
2ce20a91 135 )
0bb7bcf3
UH
136 binary = (
137 ('rx', 'RX dump'),
138 ('tx', 'TX dump'),
139 ('rxtx', 'RX/TX dump'),
140 )
96a044da 141 idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
f44d2db2 142
97cca21f 143 def putx(self, rxtx, data):
b5712ccb
PA
144 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
145 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data)
15ac6604 146
4aedd5b8 147 def putpx(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_python, data)
4aedd5b8 150
15ac6604 151 def putg(self, data):
b5712ccb
PA
152 s, halfbit = self.samplenum, self.bit_width / 2.0
153 self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data)
15ac6604
UH
154
155 def putp(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_python, data)
97cca21f 158
0bb7bcf3 159 def putbin(self, rxtx, data):
b5712ccb 160 s, halfbit = self.startsample[rxtx], self.bit_width / 2.0
2f370328 161 self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_binary, data)
0bb7bcf3 162
92b7b49f 163 def __init__(self):
f372d597 164 self.samplerate = None
f44d2db2 165 self.samplenum = 0
97cca21f
UH
166 self.frame_start = [-1, -1]
167 self.startbit = [-1, -1]
168 self.cur_data_bit = [0, 0]
169 self.databyte = [0, 0]
1ccef461 170 self.paritybit = [-1, -1]
97cca21f
UH
171 self.stopbit1 = [-1, -1]
172 self.startsample = [-1, -1]
2b716038 173 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
83be7b83 174 self.oldbit = [1, 1]
96a044da 175 self.oldpins = [-1, -1]
4aedd5b8 176 self.databits = [[], []]
f44d2db2 177
f372d597 178 def start(self):
c515eed7 179 self.out_python = self.register(srd.OUTPUT_PYTHON)
2f370328 180 self.out_binary = self.register(srd.OUTPUT_BINARY)
be465111 181 self.out_ann = self.register(srd.OUTPUT_ANN)
f44d2db2 182
f372d597
BV
183 def metadata(self, key, value):
184 if key == srd.SRD_CONF_SAMPLERATE:
35b380b1 185 self.samplerate = value
f372d597
BV
186 # The width of one UART bit in number of samples.
187 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
f44d2db2 188
f44d2db2 189 # Return true if we reached the middle of the desired bit, false otherwise.
97cca21f 190 def reached_bit(self, rxtx, bitnum):
f44d2db2
UH
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).
b5712ccb
PA
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
f44d2db2
UH
197 bitpos += bitnum * self.bit_width
198 if self.samplenum >= bitpos:
199 return True
200 return False
201
97cca21f
UH
202 def reached_bit_last(self, rxtx, bitnum):
203 bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
f44d2db2
UH
204 if self.samplenum >= bitpos:
205 return True
206 return False
207
97cca21f 208 def wait_for_start_bit(self, rxtx, old_signal, signal):
f44d2db2
UH
209 # The start bit is always 0 (low). As the idle UART (and the stop bit)
210 # level is 1 (high), the beginning of a start bit is a falling edge.
211 if not (old_signal == 1 and signal == 0):
212 return
213
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):
f44d2db2 220 # Skip samples until we're in the middle of the start bit.
97cca21f 221 if not self.reached_bit(rxtx, 0):
1bb57ab8 222 return
f44d2db2 223
97cca21f 224 self.startbit[rxtx] = signal
f44d2db2 225
5cc4b6a0 226 # The startbit must be 0. If not, we report an error.
97cca21f 227 if self.startbit[rxtx] != 0:
15ac6604 228 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
76a4498f 229 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
5cc4b6a0 230 # TODO: Abort? Ignore rest of the frame?
f44d2db2 231
97cca21f
UH
232 self.cur_data_bit[rxtx] = 0
233 self.databyte[rxtx] = 0
234 self.startsample[rxtx] = -1
f44d2db2 235
2b716038 236 self.state[rxtx] = 'GET DATA BITS'
f44d2db2 237
15ac6604 238 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
2ce20a91 239 self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
f44d2db2 240
97cca21f 241 def get_data_bits(self, rxtx, signal):
f44d2db2 242 # Skip samples until we're in the middle of the desired data bit.
97cca21f 243 if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
1bb57ab8 244 return
f44d2db2 245
15ac6604 246 # Save the sample number of the middle of the first data bit.
97cca21f
UH
247 if self.startsample[rxtx] == -1:
248 self.startsample[rxtx] = self.samplenum
f44d2db2
UH
249
250 # Get the next data bit in LSB-first or MSB-first fashion.
a7fc4c34 251 if self.options['bit_order'] == 'lsb-first':
97cca21f 252 self.databyte[rxtx] >>= 1
fd4aa8aa
UH
253 self.databyte[rxtx] |= \
254 (signal << (self.options['num_data_bits'] - 1))
22fc7ace 255 else:
97cca21f
UH
256 self.databyte[rxtx] <<= 1
257 self.databyte[rxtx] |= (signal << 0)
f44d2db2 258
4aedd5b8
UH
259 self.putg([rxtx + 12, ['%d' % signal]])
260
261 # Store individual data bits and their start/end samplenumbers.
262 s, halfbit = self.samplenum, int(self.bit_width / 2)
263 self.databits[rxtx].append([signal, s - halfbit, s + halfbit])
264
f44d2db2 265 # Return here, unless we already received all data bits.
4a04ece4 266 if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
97cca21f 267 self.cur_data_bit[rxtx] += 1
1bb57ab8 268 return
f44d2db2 269
2b716038 270 self.state[rxtx] = 'GET PARITY BIT'
f44d2db2 271
7cf698c5
UH
272 self.putpx(rxtx, ['DATA', rxtx,
273 (self.databyte[rxtx], self.databits[rxtx])])
f44d2db2 274
3006c663
UH
275 b, f = self.databyte[rxtx], self.options['format']
276 if f == 'ascii':
e0a0123d 277 c = chr(b) if b in range(30, 126 + 1) else '[%02X]' % b
8705ddc8 278 self.putx(rxtx, [rxtx, [c]])
3006c663 279 elif f == 'dec':
6d6b32d6 280 self.putx(rxtx, [rxtx, [str(b)]])
3006c663 281 elif f == 'hex':
6d6b32d6 282 self.putx(rxtx, [rxtx, [hex(b)[2:].zfill(2).upper()]])
3006c663 283 elif f == 'oct':
6d6b32d6 284 self.putx(rxtx, [rxtx, [oct(b)[2:].zfill(3)]])
3006c663 285 elif f == 'bin':
6d6b32d6 286 self.putx(rxtx, [rxtx, [bin(b)[2:].zfill(8)]])
f44d2db2 287
2824e811
UH
288 self.putbin(rxtx, [rxtx, bytes([b])])
289 self.putbin(rxtx, [2, bytes([b])])
0bb7bcf3 290
c1fc50b1 291 self.databits[rxtx] = []
4aedd5b8 292
97cca21f 293 def get_parity_bit(self, rxtx, signal):
f44d2db2 294 # If no parity is used/configured, skip to the next state immediately.
a7fc4c34 295 if self.options['parity_type'] == 'none':
2b716038 296 self.state[rxtx] = 'GET STOP BITS'
1bb57ab8 297 return
f44d2db2
UH
298
299 # Skip samples until we're in the middle of the parity bit.
4a04ece4 300 if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
1bb57ab8 301 return
f44d2db2 302
97cca21f 303 self.paritybit[rxtx] = signal
f44d2db2 304
2b716038 305 self.state[rxtx] = 'GET STOP BITS'
f44d2db2 306
ac941bf9 307 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
4a04ece4 308 self.databyte[rxtx], self.options['num_data_bits']):
15ac6604 309 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
2ce20a91 310 self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
f44d2db2 311 else:
61132abd 312 # TODO: Return expected/actual parity values.
15ac6604 313 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
4e3b276a 314 self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
f44d2db2
UH
315
316 # TODO: Currently only supports 1 stop bit.
97cca21f 317 def get_stop_bits(self, rxtx, signal):
f44d2db2 318 # Skip samples until we're in the middle of the stop bit(s).
a7fc4c34 319 skip_parity = 0 if self.options['parity_type'] == 'none' else 1
4a04ece4
UH
320 b = self.options['num_data_bits'] + 1 + skip_parity
321 if not self.reached_bit(rxtx, b):
1bb57ab8 322 return
f44d2db2 323
97cca21f 324 self.stopbit1[rxtx] = signal
f44d2db2 325
5cc4b6a0 326 # Stop bits must be 1. If not, we report an error.
97cca21f 327 if self.stopbit1[rxtx] != 1:
15ac6604 328 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
76a4498f 329 self.putg([rxtx + 10, ['Frame error', 'Frame err', 'FE']])
5cc4b6a0 330 # TODO: Abort? Ignore the frame? Other?
f44d2db2 331
2b716038 332 self.state[rxtx] = 'WAIT FOR START BIT'
f44d2db2 333
15ac6604 334 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
2ce20a91 335 self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
f44d2db2 336
decde15e 337 def decode(self, ss, es, data):
21cda951
UH
338 if not self.samplerate:
339 raise SamplerateError('Cannot decode without samplerate.')
2fcd7c22
UH
340 for (self.samplenum, pins) in data:
341
96a044da
DT
342 # We want to skip identical samples for performance reasons but,
343 # for now, we can only do that when we are in the idle state
344 # (meaning both channels are waiting for the start bit).
345 if self.state == self.idle_state and self.oldpins == pins:
346 continue
347
2fcd7c22 348 self.oldpins, (rx, tx) = pins, pins
f44d2db2 349
4eafeeef
DB
350 if self.options['invert_rx'] == 'yes':
351 rx = not rx
352 if self.options['invert_tx'] == 'yes':
353 tx = not tx
354
3dd546c1
UH
355 # Either RX or TX (but not both) can be omitted.
356 has_pin = [rx in (0, 1), tx in (0, 1)]
357 if has_pin == [False, False]:
f04964c6 358 raise ChannelError('Either TX or RX (or both) pins required.')
3dd546c1 359
f44d2db2 360 # State machine.
97cca21f 361 for rxtx in (RX, TX):
3dd546c1
UH
362 # Don't try to handle RX (or TX) if not supplied.
363 if not has_pin[rxtx]:
364 continue
365
97cca21f
UH
366 signal = rx if (rxtx == RX) else tx
367
2b716038 368 if self.state[rxtx] == 'WAIT FOR START BIT':
97cca21f 369 self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
2b716038 370 elif self.state[rxtx] == 'GET START BIT':
97cca21f 371 self.get_start_bit(rxtx, signal)
2b716038 372 elif self.state[rxtx] == 'GET DATA BITS':
97cca21f 373 self.get_data_bits(rxtx, signal)
2b716038 374 elif self.state[rxtx] == 'GET PARITY BIT':
97cca21f 375 self.get_parity_bit(rxtx, signal)
2b716038 376 elif self.state[rxtx] == 'GET STOP BITS':
97cca21f 377 self.get_stop_bits(rxtx, signal)
97cca21f
UH
378
379 # Save current RX/TX values for the next round.
380 self.oldbit[rxtx] = signal