]> sigrok.org Git - libsigrokdecode.git/blame - decoders/uart/uart.py
srd: uart: Move protocol docs to __init__.py.
[libsigrokdecode.git] / decoders / uart / uart.py
CommitLineData
f44d2db2
UH
1##
2## This file is part of the sigrok project.
3##
4a04ece4 4## Copyright (C) 2011-2012 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
21#
22# UART protocol decoder
23#
24
677d597b 25import sigrokdecode as srd
f44d2db2
UH
26
27# States
28WAIT_FOR_START_BIT = 0
29GET_START_BIT = 1
30GET_DATA_BITS = 2
31GET_PARITY_BIT = 3
32GET_STOP_BITS = 4
33
97cca21f
UH
34# Used for differentiating between the two data directions.
35RX = 0
36TX = 1
37
f44d2db2
UH
38# Parity options
39PARITY_NONE = 0
40PARITY_ODD = 1
41PARITY_EVEN = 2
42PARITY_ZERO = 3
43PARITY_ONE = 4
44
45# Stop bit options
46STOP_BITS_0_5 = 0
47STOP_BITS_1 = 1
48STOP_BITS_1_5 = 2
49STOP_BITS_2 = 3
50
51# Bit order options
52LSB_FIRST = 0
53MSB_FIRST = 1
54
1bb57ab8
UH
55# Annotation feed formats
56ANN_ASCII = 0
57ANN_DEC = 1
58ANN_HEX = 2
59ANN_OCT = 3
60ANN_BITS = 4
f44d2db2 61
f44d2db2
UH
62# Given a parity type to check (odd, even, zero, one), the value of the
63# parity bit, the value of the data, and the length of the data (5-9 bits,
64# usually 8 bits) return True if the parity is correct, False otherwise.
65# PARITY_NONE is _not_ allowed as value for 'parity_type'.
66def parity_ok(parity_type, parity_bit, data, num_data_bits):
67
68 # Handle easy cases first (parity bit is always 1 or 0).
69 if parity_type == PARITY_ZERO:
70 return parity_bit == 0
71 elif parity_type == PARITY_ONE:
72 return parity_bit == 1
73
74 # Count number of 1 (high) bits in the data (and the parity bit itself!).
ac941bf9 75 ones = bin(data).count('1') + parity_bit
f44d2db2
UH
76
77 # Check for odd/even parity.
78 if parity_type == PARITY_ODD:
ac941bf9 79 return (ones % 2) == 1
f44d2db2 80 elif parity_type == PARITY_EVEN:
ac941bf9 81 return (ones % 2) == 0
f44d2db2
UH
82 else:
83 raise Exception('Invalid parity type: %d' % parity_type)
84
677d597b 85class Decoder(srd.Decoder):
a2c2afd9 86 api_version = 1
f44d2db2
UH
87 id = 'uart'
88 name = 'UART'
3d3da57d 89 longname = 'Universal Asynchronous Receiver/Transmitter'
f44d2db2
UH
90 desc = 'Universal Asynchronous Receiver/Transmitter (UART)'
91 longdesc = 'TODO.'
f44d2db2
UH
92 license = 'gplv2+'
93 inputs = ['logic']
94 outputs = ['uart']
29ed0f4c 95 probes = [
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'},
100 ]
b77614bc 101 optional_probes = []
f44d2db2 102 options = {
97cca21f 103 'baudrate': ['Baud rate', 115200],
f44d2db2 104 'num_data_bits': ['Data bits', 8], # Valid: 5-9.
ac941bf9
UH
105 'parity_type': ['Parity type', PARITY_NONE],
106 'parity_check': ['Check parity?', True], # TODO: Bool supported?
f44d2db2
UH
107 'num_stop_bits': ['Stop bit(s)', STOP_BITS_1],
108 'bit_order': ['Bit order', LSB_FIRST],
f44d2db2 109 # TODO: Options to invert the signal(s).
f44d2db2 110 }
e97b6ef5 111 annotations = [
97cca21f
UH
112 ['ASCII', 'Data bytes as ASCII characters'],
113 ['Decimal', 'Databytes as decimal, integer values'],
114 ['Hex', 'Data bytes in hex format'],
115 ['Octal', 'Data bytes as octal numbers'],
116 ['Bits', 'Data bytes in bit notation (sequence of 0/1 digits)'],
1bb57ab8 117 ]
f44d2db2 118
97cca21f
UH
119 def putx(self, rxtx, data):
120 self.put(self.startsample[rxtx], self.samplenum - 1, self.out_ann, data)
121
f44d2db2 122 def __init__(self, **kwargs):
f44d2db2 123 self.samplenum = 0
97cca21f
UH
124 self.frame_start = [-1, -1]
125 self.startbit = [-1, -1]
126 self.cur_data_bit = [0, 0]
127 self.databyte = [0, 0]
1ccef461 128 self.paritybit = [-1, -1]
97cca21f
UH
129 self.stopbit1 = [-1, -1]
130 self.startsample = [-1, -1]
f44d2db2
UH
131
132 # Initial state.
97cca21f 133 self.state = [WAIT_FOR_START_BIT, WAIT_FOR_START_BIT]
f44d2db2 134
97cca21f 135 self.oldbit = [None, None]
f44d2db2
UH
136
137 def start(self, metadata):
f44d2db2 138 self.samplerate = metadata['samplerate']
56202222
UH
139 self.out_proto = self.add(srd.OUTPUT_PROTO, 'uart')
140 self.out_ann = self.add(srd.OUTPUT_ANN, 'uart')
f44d2db2 141
f44d2db2 142 # The width of one UART bit in number of samples.
4a04ece4
UH
143 self.bit_width = \
144 float(self.samplerate) / float(self.options['baudrate'])
f44d2db2
UH
145
146 def report(self):
147 pass
148
149 # Return true if we reached the middle of the desired bit, false otherwise.
97cca21f 150 def reached_bit(self, rxtx, bitnum):
f44d2db2
UH
151 # bitpos is the samplenumber which is in the middle of the
152 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
153 # (if used) or the first stop bit, and so on).
97cca21f 154 bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
f44d2db2
UH
155 bitpos += bitnum * self.bit_width
156 if self.samplenum >= bitpos:
157 return True
158 return False
159
97cca21f
UH
160 def reached_bit_last(self, rxtx, bitnum):
161 bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
f44d2db2
UH
162 if self.samplenum >= bitpos:
163 return True
164 return False
165
97cca21f 166 def wait_for_start_bit(self, rxtx, old_signal, signal):
f44d2db2
UH
167 # The start bit is always 0 (low). As the idle UART (and the stop bit)
168 # level is 1 (high), the beginning of a start bit is a falling edge.
169 if not (old_signal == 1 and signal == 0):
170 return
171
172 # Save the sample number where the start bit begins.
97cca21f 173 self.frame_start[rxtx] = self.samplenum
f44d2db2 174
97cca21f 175 self.state[rxtx] = GET_START_BIT
f44d2db2 176
97cca21f 177 def get_start_bit(self, rxtx, signal):
f44d2db2 178 # Skip samples until we're in the middle of the start bit.
97cca21f 179 if not self.reached_bit(rxtx, 0):
1bb57ab8 180 return
f44d2db2 181
97cca21f 182 self.startbit[rxtx] = signal
f44d2db2 183
5cc4b6a0 184 # The startbit must be 0. If not, we report an error.
97cca21f
UH
185 if self.startbit[rxtx] != 0:
186 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
b9e44d1e 187 ['INVALID STARTBIT', rxtx, self.startbit[rxtx]])
5cc4b6a0 188 # TODO: Abort? Ignore rest of the frame?
f44d2db2 189
97cca21f
UH
190 self.cur_data_bit[rxtx] = 0
191 self.databyte[rxtx] = 0
192 self.startsample[rxtx] = -1
f44d2db2 193
97cca21f 194 self.state[rxtx] = GET_DATA_BITS
f44d2db2 195
97cca21f 196 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
b9e44d1e 197 ['STARTBIT', rxtx, self.startbit[rxtx]])
97cca21f 198 self.put(self.frame_start[rxtx], self.samplenum, self.out_ann,
5cc4b6a0 199 [ANN_ASCII, ['Start bit', 'Start', 'S']])
f44d2db2 200
97cca21f 201 def get_data_bits(self, rxtx, signal):
f44d2db2 202 # Skip samples until we're in the middle of the desired data bit.
97cca21f 203 if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
1bb57ab8 204 return
f44d2db2
UH
205
206 # Save the sample number where the data byte starts.
97cca21f
UH
207 if self.startsample[rxtx] == -1:
208 self.startsample[rxtx] = self.samplenum
f44d2db2
UH
209
210 # Get the next data bit in LSB-first or MSB-first fashion.
4a04ece4 211 if self.options['bit_order'] == LSB_FIRST:
97cca21f 212 self.databyte[rxtx] >>= 1
fd4aa8aa
UH
213 self.databyte[rxtx] |= \
214 (signal << (self.options['num_data_bits'] - 1))
4a04ece4 215 elif self.options['bit_order'] == MSB_FIRST:
97cca21f
UH
216 self.databyte[rxtx] <<= 1
217 self.databyte[rxtx] |= (signal << 0)
f44d2db2 218 else:
4a04ece4
UH
219 raise Exception('Invalid bit order value: %d',
220 self.options['bit_order'])
f44d2db2
UH
221
222 # Return here, unless we already received all data bits.
4a04ece4
UH
223 # TODO? Off-by-one?
224 if self.cur_data_bit[rxtx] < self.options['num_data_bits'] - 1:
97cca21f 225 self.cur_data_bit[rxtx] += 1
1bb57ab8 226 return
f44d2db2 227
97cca21f 228 self.state[rxtx] = GET_PARITY_BIT
f44d2db2 229
97cca21f 230 self.put(self.startsample[rxtx], self.samplenum - 1, self.out_proto,
b9e44d1e 231 ['DATA', rxtx, self.databyte[rxtx]])
f44d2db2 232
97cca21f
UH
233 s = 'RX: ' if (rxtx == RX) else 'TX: '
234 self.putx(rxtx, [ANN_ASCII, [s + chr(self.databyte[rxtx])]])
235 self.putx(rxtx, [ANN_DEC, [s + str(self.databyte[rxtx])]])
236 self.putx(rxtx, [ANN_HEX, [s + hex(self.databyte[rxtx]),
237 s + hex(self.databyte[rxtx])[2:]]])
238 self.putx(rxtx, [ANN_OCT, [s + oct(self.databyte[rxtx]),
239 s + oct(self.databyte[rxtx])[2:]]])
240 self.putx(rxtx, [ANN_BITS, [s + bin(self.databyte[rxtx]),
241 s + bin(self.databyte[rxtx])[2:]]])
f44d2db2 242
97cca21f 243 def get_parity_bit(self, rxtx, signal):
f44d2db2 244 # If no parity is used/configured, skip to the next state immediately.
ac941bf9 245 if self.options['parity_type'] == PARITY_NONE:
97cca21f 246 self.state[rxtx] = GET_STOP_BITS
1bb57ab8 247 return
f44d2db2
UH
248
249 # Skip samples until we're in the middle of the parity bit.
4a04ece4 250 if not self.reached_bit(rxtx, self.options['num_data_bits'] + 1):
1bb57ab8 251 return
f44d2db2 252
97cca21f 253 self.paritybit[rxtx] = signal
f44d2db2 254
97cca21f 255 self.state[rxtx] = GET_STOP_BITS
f44d2db2 256
ac941bf9 257 if parity_ok(self.options['parity_type'], self.paritybit[rxtx],
4a04ece4 258 self.databyte[rxtx], self.options['num_data_bits']):
f44d2db2 259 # TODO: Fix range.
1bb57ab8 260 self.put(self.samplenum, self.samplenum, self.out_proto,
b9e44d1e 261 ['PARITYBIT', rxtx, self.paritybit[rxtx]])
1bb57ab8 262 self.put(self.samplenum, self.samplenum, self.out_ann,
5cc4b6a0 263 [ANN_ASCII, ['Parity bit', 'Parity', 'P']])
f44d2db2 264 else:
1bb57ab8 265 # TODO: Fix range.
61132abd 266 # TODO: Return expected/actual parity values.
1bb57ab8 267 self.put(self.samplenum, self.samplenum, self.out_proto,
b9e44d1e 268 ['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple...
1bb57ab8 269 self.put(self.samplenum, self.samplenum, self.out_ann,
5cc4b6a0 270 [ANN_ASCII, ['Parity error', 'Parity err', 'PE']])
f44d2db2
UH
271
272 # TODO: Currently only supports 1 stop bit.
97cca21f 273 def get_stop_bits(self, rxtx, signal):
f44d2db2 274 # Skip samples until we're in the middle of the stop bit(s).
ac941bf9 275 skip_parity = 0 if self.options['parity_type'] == PARITY_NONE else 1
4a04ece4
UH
276 b = self.options['num_data_bits'] + 1 + skip_parity
277 if not self.reached_bit(rxtx, b):
1bb57ab8 278 return
f44d2db2 279
97cca21f 280 self.stopbit1[rxtx] = signal
f44d2db2 281
5cc4b6a0 282 # Stop bits must be 1. If not, we report an error.
97cca21f
UH
283 if self.stopbit1[rxtx] != 1:
284 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
b9e44d1e 285 ['INVALID STOPBIT', rxtx, self.stopbit1[rxtx]])
5cc4b6a0 286 # TODO: Abort? Ignore the frame? Other?
f44d2db2 287
97cca21f 288 self.state[rxtx] = WAIT_FOR_START_BIT
f44d2db2 289
f44d2db2 290 # TODO: Fix range.
1bb57ab8 291 self.put(self.samplenum, self.samplenum, self.out_proto,
b9e44d1e 292 ['STOPBIT', rxtx, self.stopbit1[rxtx]])
1bb57ab8 293 self.put(self.samplenum, self.samplenum, self.out_ann,
5cc4b6a0 294 [ANN_ASCII, ['Stop bit', 'Stop', 'P']])
f44d2db2 295
decde15e
UH
296 def decode(self, ss, es, data):
297 # TODO: Either RX or TX could be omitted (optional probe).
97cca21f 298 for (samplenum, (rx, tx)) in data:
f44d2db2
UH
299
300 # TODO: Start counting at 0 or 1? Increase before or after?
301 self.samplenum += 1
302
303 # First sample: Save RX/TX value.
97cca21f
UH
304 if self.oldbit[RX] == None:
305 self.oldbit[RX] = rx
306 continue
307 if self.oldbit[TX] == None:
308 self.oldbit[TX] = tx
f44d2db2
UH
309 continue
310
f44d2db2 311 # State machine.
97cca21f
UH
312 for rxtx in (RX, TX):
313 signal = rx if (rxtx == RX) else tx
314
315 if self.state[rxtx] == WAIT_FOR_START_BIT:
316 self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
317 elif self.state[rxtx] == GET_START_BIT:
318 self.get_start_bit(rxtx, signal)
319 elif self.state[rxtx] == GET_DATA_BITS:
320 self.get_data_bits(rxtx, signal)
321 elif self.state[rxtx] == GET_PARITY_BIT:
322 self.get_parity_bit(rxtx, signal)
323 elif self.state[rxtx] == GET_STOP_BITS:
324 self.get_stop_bits(rxtx, signal)
325 else:
decde15e 326 raise Exception('Invalid state: %d' % self.state[rxtx])
97cca21f
UH
327
328 # Save current RX/TX values for the next round.
329 self.oldbit[rxtx] = signal
f44d2db2 330