]> sigrok.org Git - libsigrokdecode.git/blame - decoders/uart/pd.py
sdcard_spi: Define annotation rows.
[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
f44d2db2 22
4cace3b8 23'''
c515eed7 24OUTPUT_PYTHON format:
4cace3b8
UH
25
26UART packet:
27[<packet-type>, <rxtx>, <packet-data>]
28
29This is the list of <packet-type>s and their respective <packet-data>:
30 - 'STARTBIT': The data is the (integer) value of the start bit (0/1).
31 - 'DATA': The data is the (integer) value of the UART data. Valid values
32 range from 0 to 512 (as the data can be up to 9 bits in size).
33 - 'PARITYBIT': The data is the (integer) value of the parity bit (0/1).
34 - 'STOPBIT': The data is the (integer) value of the stop bit (0 or 1).
35 - 'INVALID STARTBIT': The data is the (integer) value of the start bit (0/1).
36 - 'INVALID STOPBIT': The data is the (integer) value of the stop bit (0/1).
37 - 'PARITY ERROR': The data is a tuple with two entries. The first one is
38 the expected parity value, the second is the actual parity value.
39 - TODO: Frame error?
40
41The <rxtx> field is 0 for RX packets, 1 for TX packets.
42'''
43
97cca21f
UH
44# Used for differentiating between the two data directions.
45RX = 0
46TX = 1
47
f44d2db2
UH
48# Given a parity type to check (odd, even, zero, one), the value of the
49# parity bit, the value of the data, and the length of the data (5-9 bits,
50# usually 8 bits) return True if the parity is correct, False otherwise.
a7fc4c34 51# 'none' is _not_ allowed as value for 'parity_type'.
f44d2db2
UH
52def parity_ok(parity_type, parity_bit, data, num_data_bits):
53
54 # Handle easy cases first (parity bit is always 1 or 0).
a7fc4c34 55 if parity_type == 'zero':
f44d2db2 56 return parity_bit == 0
a7fc4c34 57 elif parity_type == 'one':
f44d2db2
UH
58 return parity_bit == 1
59
60 # Count number of 1 (high) bits in the data (and the parity bit itself!).
ac941bf9 61 ones = bin(data).count('1') + parity_bit
f44d2db2
UH
62
63 # Check for odd/even parity.
a7fc4c34 64 if parity_type == 'odd':
ac941bf9 65 return (ones % 2) == 1
a7fc4c34 66 elif parity_type == 'even':
ac941bf9 67 return (ones % 2) == 0
f44d2db2
UH
68 else:
69 raise Exception('Invalid parity type: %d' % parity_type)
70
677d597b 71class Decoder(srd.Decoder):
a2c2afd9 72 api_version = 1
f44d2db2
UH
73 id = 'uart'
74 name = 'UART'
3d3da57d 75 longname = 'Universal Asynchronous Receiver/Transmitter'
a465436e 76 desc = 'Asynchronous, serial bus.'
f44d2db2
UH
77 license = 'gplv2+'
78 inputs = ['logic']
79 outputs = ['uart']
3dd546c1
UH
80 probes = []
81 optional_probes = [
f44d2db2
UH
82 # Allow specifying only one of the signals, e.g. if only one data
83 # direction exists (or is relevant).
29ed0f4c
UH
84 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
85 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
86 ]
f44d2db2 87 options = {
97cca21f 88 'baudrate': ['Baud rate', 115200],
f44d2db2 89 'num_data_bits': ['Data bits', 8], # Valid: 5-9.
a7fc4c34
UH
90 'parity_type': ['Parity type', 'none'],
91 'parity_check': ['Check parity?', 'yes'], # TODO: Bool supported?
92 'num_stop_bits': ['Stop bit(s)', '1'], # String! 0, 0.5, 1, 1.5.
93 'bit_order': ['Bit order', 'lsb-first'],
3006c663 94 'format': ['Data format', 'ascii'], # ascii/dec/hex/oct/bin
f44d2db2 95 # TODO: Options to invert the signal(s).
f44d2db2 96 }
e97b6ef5 97 annotations = [
2ce20a91
UH
98 ['rx-data', 'RX data'],
99 ['tx-data', 'TX data'],
4e3b276a
UH
100 ['rx-start', 'RX start bits'],
101 ['tx-start', 'TX start bits'],
102 ['rx-parity-ok', 'RX parity OK bits'],
103 ['tx-parity-ok', 'TX parity OK bits'],
104 ['rx-parity-err', 'RX parity error bits'],
105 ['tx-parity-err', 'TX parity error bits'],
106 ['rx-stop', 'RX stop bits'],
107 ['tx-stop', 'TX stop bits'],
2ce20a91
UH
108 ['rx-warnings', 'RX warnings'],
109 ['tx-warnings', 'TX warnings'],
1bb57ab8 110 ]
2ce20a91 111 annotation_rows = (
4e3b276a
UH
112 ('rx-data', 'RX', (0, 2, 4, 6, 8)),
113 ('tx-data', 'TX', (1, 3, 5, 7, 9)),
114 ('rx-warnings', 'RX warnings', (10,)),
115 ('tx-warnings', 'TX warnings', (11,)),
2ce20a91 116 )
0bb7bcf3
UH
117 binary = (
118 ('rx', 'RX dump'),
119 ('tx', 'TX dump'),
120 ('rxtx', 'RX/TX dump'),
121 )
f44d2db2 122
97cca21f 123 def putx(self, rxtx, data):
15ac6604
UH
124 s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
125 self.put(s - halfbit, self.samplenum + halfbit, self.out_ann, data)
126
127 def putg(self, data):
128 s, halfbit = self.samplenum, int(self.bit_width / 2)
129 self.put(s - halfbit, s + halfbit, self.out_ann, data)
130
131 def putp(self, data):
132 s, halfbit = self.samplenum, int(self.bit_width / 2)
c515eed7 133 self.put(s - halfbit, s + halfbit, self.out_python, data)
97cca21f 134
0bb7bcf3
UH
135 def putbin(self, rxtx, data):
136 s, halfbit = self.startsample[rxtx], int(self.bit_width / 2)
137 self.put(s - halfbit, self.samplenum + halfbit, self.out_bin, data)
138
f44d2db2 139 def __init__(self, **kwargs):
f372d597 140 self.samplerate = None
f44d2db2 141 self.samplenum = 0
97cca21f
UH
142 self.frame_start = [-1, -1]
143 self.startbit = [-1, -1]
144 self.cur_data_bit = [0, 0]
145 self.databyte = [0, 0]
1ccef461 146 self.paritybit = [-1, -1]
97cca21f
UH
147 self.stopbit1 = [-1, -1]
148 self.startsample = [-1, -1]
2b716038 149 self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT']
83be7b83
UH
150 self.oldbit = [1, 1]
151 self.oldpins = [1, 1]
f44d2db2 152
f372d597 153 def start(self):
c515eed7 154 self.out_python = self.register(srd.OUTPUT_PYTHON)
0bb7bcf3 155 self.out_bin = self.register(srd.OUTPUT_BINARY)
be465111 156 self.out_ann = self.register(srd.OUTPUT_ANN)
f44d2db2 157
f372d597
BV
158 def metadata(self, key, value):
159 if key == srd.SRD_CONF_SAMPLERATE:
160 self.samplerate = value;
161 # The width of one UART bit in number of samples.
162 self.bit_width = float(self.samplerate) / float(self.options['baudrate'])
f44d2db2 163
f44d2db2 164 # Return true if we reached the middle of the desired bit, false otherwise.
97cca21f 165 def reached_bit(self, rxtx, bitnum):
f44d2db2
UH
166 # bitpos is the samplenumber which is in the middle of the
167 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
168 # (if used) or the first stop bit, and so on).
97cca21f 169 bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
f44d2db2
UH
170 bitpos += bitnum * self.bit_width
171 if self.samplenum >= bitpos:
172 return True
173 return False
174
97cca21f
UH
175 def reached_bit_last(self, rxtx, bitnum):
176 bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
f44d2db2
UH
177 if self.samplenum >= bitpos:
178 return True
179 return False
180
97cca21f 181 def wait_for_start_bit(self, rxtx, old_signal, signal):
f44d2db2
UH
182 # The start bit is always 0 (low). As the idle UART (and the stop bit)
183 # level is 1 (high), the beginning of a start bit is a falling edge.
184 if not (old_signal == 1 and signal == 0):
185 return
186
187 # Save the sample number where the start bit begins.
97cca21f 188 self.frame_start[rxtx] = self.samplenum
f44d2db2 189
2b716038 190 self.state[rxtx] = 'GET START BIT'
f44d2db2 191
97cca21f 192 def get_start_bit(self, rxtx, signal):
f44d2db2 193 # Skip samples until we're in the middle of the start bit.
97cca21f 194 if not self.reached_bit(rxtx, 0):
1bb57ab8 195 return
f44d2db2 196
97cca21f 197 self.startbit[rxtx] = signal
f44d2db2 198
5cc4b6a0 199 # The startbit must be 0. If not, we report an error.
97cca21f 200 if self.startbit[rxtx] != 0:
15ac6604 201 self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
5cc4b6a0 202 # TODO: Abort? Ignore rest of the frame?
f44d2db2 203
97cca21f
UH
204 self.cur_data_bit[rxtx] = 0
205 self.databyte[rxtx] = 0
206 self.startsample[rxtx] = -1
f44d2db2 207
2b716038 208 self.state[rxtx] = 'GET DATA BITS'
f44d2db2 209
15ac6604 210 self.putp(['STARTBIT', rxtx, self.startbit[rxtx]])
2ce20a91 211 self.putg([rxtx + 2, ['Start bit', 'Start', 'S']])
f44d2db2 212
97cca21f 213 def get_data_bits(self, rxtx, signal):
f44d2db2 214 # Skip samples until we're in the middle of the desired data bit.
97cca21f 215 if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
1bb57ab8 216 return
f44d2db2 217
15ac6604 218 # Save the sample number of the middle of the first data bit.
97cca21f
UH
219 if self.startsample[rxtx] == -1:
220 self.startsample[rxtx] = self.samplenum
f44d2db2
UH
221
222 # Get the next data bit in LSB-first or MSB-first fashion.
a7fc4c34 223 if self.options['bit_order'] == 'lsb-first':
97cca21f 224 self.databyte[rxtx] >>= 1
fd4aa8aa
UH
225 self.databyte[rxtx] |= \
226 (signal << (self.options['num_data_bits'] - 1))
a7fc4c34 227 elif self.options['bit_order'] == 'msb-first':
97cca21f
UH
228 self.databyte[rxtx] <<= 1
229 self.databyte[rxtx] |= (signal << 0)
f44d2db2 230 else:
a7fc4c34 231 raise Exception('Invalid bit order value: %s',
4a04ece4 232 self.options['bit_order'])
f44d2db2
UH
233
234 # Return here, unless we already received all data bits.
4a04ece4 235 if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
97cca21f 236 self.cur_data_bit[rxtx] += 1
1bb57ab8 237 return
f44d2db2 238
2b716038 239 self.state[rxtx] = 'GET PARITY BIT'
f44d2db2 240
15ac6604 241 self.putp(['DATA', rxtx, self.databyte[rxtx]])
f44d2db2 242
3006c663
UH
243 b, f = self.databyte[rxtx], self.options['format']
244 if f == 'ascii':
e0a0123d 245 c = chr(b) if b in range(30, 126 + 1) else '[%02X]' % b
8705ddc8 246 self.putx(rxtx, [rxtx, [c]])
3006c663 247 elif f == 'dec':
6d6b32d6 248 self.putx(rxtx, [rxtx, [str(b)]])
3006c663 249 elif f == 'hex':
6d6b32d6 250 self.putx(rxtx, [rxtx, [hex(b)[2:].zfill(2).upper()]])
3006c663 251 elif f == 'oct':
6d6b32d6 252 self.putx(rxtx, [rxtx, [oct(b)[2:].zfill(3)]])
3006c663 253 elif f == 'bin':
6d6b32d6 254 self.putx(rxtx, [rxtx, [bin(b)[2:].zfill(8)]])
3006c663
UH
255 else:
256 raise Exception('Invalid data format option: %s' % f)
f44d2db2 257
0bb7bcf3
UH
258 self.putbin(rxtx, (rxtx, bytes([b])))
259 self.putbin(rxtx, (2, bytes([b])))
260
97cca21f 261 def get_parity_bit(self, rxtx, signal):
f44d2db2 262 # If no parity is used/configured, skip to the next state immediately.
a7fc4c34 263 if self.options['parity_type'] == 'none':
2b716038 264 self.state[rxtx] = 'GET STOP BITS'
1bb57ab8 265 return
f44d2db2
UH
266
267 # Skip samples until we're in the middle of the parity bit.
4a04ece4 268 if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
1bb57ab8 269 return
f44d2db2 270
97cca21f 271 self.paritybit[rxtx] = signal
f44d2db2 272
2b716038 273 self.state[rxtx] = 'GET STOP BITS'
f44d2db2 274
ac941bf9 275 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
4a04ece4 276 self.databyte[rxtx], self.options['num_data_bits']):
15ac6604 277 self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]])
2ce20a91 278 self.putg([rxtx + 4, ['Parity bit', 'Parity', 'P']])
f44d2db2 279 else:
61132abd 280 # TODO: Return expected/actual parity values.
15ac6604 281 self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
4e3b276a 282 self.putg([rxtx + 6, ['Parity error', 'Parity err', 'PE']])
f44d2db2
UH
283
284 # TODO: Currently only supports 1 stop bit.
97cca21f 285 def get_stop_bits(self, rxtx, signal):
f44d2db2 286 # Skip samples until we're in the middle of the stop bit(s).
a7fc4c34 287 skip_parity = 0 if self.options['parity_type'] == 'none' else 1
4a04ece4
UH
288 b = self.options['num_data_bits'] + 1 + skip_parity
289 if not self.reached_bit(rxtx, b):
1bb57ab8 290 return
f44d2db2 291
97cca21f 292 self.stopbit1[rxtx] = signal
f44d2db2 293
5cc4b6a0 294 # Stop bits must be 1. If not, we report an error.
97cca21f 295 if self.stopbit1[rxtx] != 1:
15ac6604 296 self.putp(['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
4e3b276a 297 self.putg([rxtx + 8, ['Frame error', 'Frame err', 'FE']])
5cc4b6a0 298 # TODO: Abort? Ignore the frame? Other?
f44d2db2 299
2b716038 300 self.state[rxtx] = 'WAIT FOR START BIT'
f44d2db2 301
15ac6604 302 self.putp(['STOPBIT', rxtx, self.stopbit1[rxtx]])
2ce20a91 303 self.putg([rxtx + 4, ['Stop bit', 'Stop', 'T']])
f44d2db2 304
decde15e 305 def decode(self, ss, es, data):
f372d597
BV
306 if self.samplerate is None:
307 raise Exception("Cannot decode without samplerate.")
2fcd7c22
UH
308 for (self.samplenum, pins) in data:
309
b0827236
UH
310 # Note: Ignoring identical samples here for performance reasons
311 # is not possible for this PD, at least not in the current state.
312 # if self.oldpins == pins:
313 # continue
2fcd7c22 314 self.oldpins, (rx, tx) = pins, pins
f44d2db2 315
3dd546c1
UH
316 # Either RX or TX (but not both) can be omitted.
317 has_pin = [rx in (0, 1), tx in (0, 1)]
318 if has_pin == [False, False]:
319 raise Exception('Either TX or RX (or both) pins required.')
320
f44d2db2 321 # State machine.
97cca21f 322 for rxtx in (RX, TX):
3dd546c1
UH
323 # Don't try to handle RX (or TX) if not supplied.
324 if not has_pin[rxtx]:
325 continue
326
97cca21f
UH
327 signal = rx if (rxtx == RX) else tx
328
2b716038 329 if self.state[rxtx] == 'WAIT FOR START BIT':
97cca21f 330 self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
2b716038 331 elif self.state[rxtx] == 'GET START BIT':
97cca21f 332 self.get_start_bit(rxtx, signal)
2b716038 333 elif self.state[rxtx] == 'GET DATA BITS':
97cca21f 334 self.get_data_bits(rxtx, signal)
2b716038 335 elif self.state[rxtx] == 'GET PARITY BIT':
97cca21f 336 self.get_parity_bit(rxtx, signal)
2b716038 337 elif self.state[rxtx] == 'GET STOP BITS':
97cca21f
UH
338 self.get_stop_bits(rxtx, signal)
339 else:
0eeeb544 340 raise Exception('Invalid state: %s' % self.state[rxtx])
97cca21f
UH
341
342 # Save current RX/TX values for the next round.
343 self.oldbit[rxtx] = signal
f44d2db2 344