]> sigrok.org Git - libsigrokdecode.git/blame - decoders/uart/uart.py
I2C: no need to copy default option values over from the class
[libsigrokdecode.git] / decoders / uart / uart.py
CommitLineData
f44d2db2
UH
1##
2## This file is part of the sigrok project.
3##
4## Copyright (C) 2011 Uwe Hermann <uwe@hermann-uwe.de>
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
6efe1e11
UH
25#
26# Universal Asynchronous Receiver Transmitter (UART) is a simple serial
27# communication protocol which allows two devices to talk to each other.
28#
29# It uses just two data signals and a ground (GND) signal:
30# - RX/RXD: Receive signal
31# - TX/TXD: Transmit signal
32#
33# The protocol is asynchronous, i.e., there is no dedicated clock signal.
34# Rather, both devices have to agree on a baudrate (number of bits to be
35# transmitted per second) beforehand. Baudrates can be arbitrary in theory,
36# but usually the choice is limited by the hardware UARTs that are used.
37# Common values are 9600 or 115200.
38#
39# The protocol allows full-duplex transmission, i.e. both devices can send
40# data at the same time. However, unlike SPI (which is always full-duplex,
41# i.e., each send operation is automatically also a receive operation), UART
42# allows one-way communication, too. In such a case only one signal (and GND)
43# is required.
44#
45# The data is sent over the TX line in so-called 'frames', which consist of:
46# - Exactly one start bit (always 0/low).
47# - Between 5 and 9 data bits.
48# - An (optional) parity bit.
49# - One or more stop bit(s).
50#
51# The idle state of the RX/TX line is 1/high. As the start bit is 0/low, the
52# receiver can continually monitor its RX line for a falling edge, in order
53# to detect the start bit.
54#
55# Once detected, it can (due to the agreed-upon baudrate and thus the known
56# width/duration of one UART bit) sample the state of the RX line "in the
57# middle" of each (start/data/parity/stop) bit it wants to analyze.
58#
59# It is configurable whether there is a parity bit in a frame, and if yes,
60# which type of parity is used:
61# - None: No parity bit is included.
62# - Odd: The number of 1 bits in the data (and parity bit itself) is odd.
63# - Even: The number of 1 bits in the data (and parity bit itself) is even.
64# - Mark/one: The parity bit is always 1/high (also called 'mark state').
65# - Space/zero: The parity bit is always 0/low (also called 'space state').
66#
67# It is also configurable how many stop bits are to be used:
68# - 1 stop bit (most common case)
69# - 2 stop bits
70# - 1.5 stop bits (i.e., one stop bit, but 1.5 times the UART bit width)
71# - 0.5 stop bits (i.e., one stop bit, but 0.5 times the UART bit width)
72#
73# The bit order of the 5-9 data bits is LSB-first.
74#
75# Possible special cases:
76# - One or both data lines could be inverted, which also means that the idle
77# state of the signal line(s) is low instead of high.
78# - Only the data bits on one or both data lines (and the parity bit) could
79# be inverted (but the start/stop bits remain non-inverted).
80# - The bit order could be MSB-first instead of LSB-first.
81# - The baudrate could change in the middle of the communication. This only
82# happens in very special cases, and can only work if both devices know
83# to which baudrate they are to switch, and when.
84# - Theoretically, the baudrate on RX and the one on TX could also be
85# different, but that's a very obscure case and probably doesn't happen
86# very often in practice.
87#
88# Error conditions:
89# - If there is a parity bit, but it doesn't match the expected parity,
90# this is called a 'parity error'.
91# - If there are no stop bit(s), that's called a 'frame error'.
92#
93# More information:
94# TODO: URLs
95#
96
61132abd
UH
97#
98# Protocol output format:
61132abd 99#
97cca21f
UH
100# UART packet:
101# [<packet-type>, <rxtx>, <packet-data>]
61132abd 102#
97cca21f 103# This is the list of <packet-types>s and their respective <packet-data>:
61132abd
UH
104# - T_START: The data is the (integer) value of the start bit (0 or 1).
105# - T_DATA: The data is the (integer) value of the UART data. Valid values
106# range from 0 to 512 (as the data can be up to 9 bits in size).
107# - T_PARITY: The data is the (integer) value of the parity bit (0 or 1).
108# - T_STOP: The data is the (integer) value of the stop bit (0 or 1).
109# - T_INVALID_START: The data is the (integer) value of the start bit (0 or 1).
110# - T_INVALID_STOP: The data is the (integer) value of the stop bit (0 or 1).
111# - T_PARITY_ERROR: The data is a tuple with two entries. The first one is
112# the expected parity value, the second is the actual parity value.
113#
97cca21f 114# The <rxtx> field is 0 for RX packets, 1 for TX packets.
61132abd
UH
115#
116
677d597b 117import sigrokdecode as srd
f44d2db2
UH
118
119# States
120WAIT_FOR_START_BIT = 0
121GET_START_BIT = 1
122GET_DATA_BITS = 2
123GET_PARITY_BIT = 3
124GET_STOP_BITS = 4
125
97cca21f
UH
126# Used for differentiating between the two data directions.
127RX = 0
128TX = 1
129
f44d2db2
UH
130# Parity options
131PARITY_NONE = 0
132PARITY_ODD = 1
133PARITY_EVEN = 2
134PARITY_ZERO = 3
135PARITY_ONE = 4
136
137# Stop bit options
138STOP_BITS_0_5 = 0
139STOP_BITS_1 = 1
140STOP_BITS_1_5 = 2
141STOP_BITS_2 = 3
142
143# Bit order options
144LSB_FIRST = 0
145MSB_FIRST = 1
146
1bb57ab8
UH
147# Annotation feed formats
148ANN_ASCII = 0
149ANN_DEC = 1
150ANN_HEX = 2
151ANN_OCT = 3
152ANN_BITS = 4
f44d2db2 153
61132abd
UH
154# Protocol output packet types
155T_START = 0
156T_DATA = 1
157T_PARITY = 2
158T_STOP = 3
159T_INVALID_START = 4
160T_INVALID_STOP = 5
161T_PARITY_ERROR = 6
162
f44d2db2
UH
163# Given a parity type to check (odd, even, zero, one), the value of the
164# parity bit, the value of the data, and the length of the data (5-9 bits,
165# usually 8 bits) return True if the parity is correct, False otherwise.
166# PARITY_NONE is _not_ allowed as value for 'parity_type'.
167def parity_ok(parity_type, parity_bit, data, num_data_bits):
168
169 # Handle easy cases first (parity bit is always 1 or 0).
170 if parity_type == PARITY_ZERO:
171 return parity_bit == 0
172 elif parity_type == PARITY_ONE:
173 return parity_bit == 1
174
175 # Count number of 1 (high) bits in the data (and the parity bit itself!).
176 parity = bin(data).count('1') + parity_bit
177
178 # Check for odd/even parity.
179 if parity_type == PARITY_ODD:
180 return (parity % 2) == 1
181 elif parity_type == PARITY_EVEN:
182 return (parity % 2) == 0
183 else:
184 raise Exception('Invalid parity type: %d' % parity_type)
185
677d597b 186class Decoder(srd.Decoder):
a2c2afd9 187 api_version = 1
f44d2db2
UH
188 id = 'uart'
189 name = 'UART'
3d3da57d 190 longname = 'Universal Asynchronous Receiver/Transmitter'
f44d2db2
UH
191 desc = 'Universal Asynchronous Receiver/Transmitter (UART)'
192 longdesc = 'TODO.'
f44d2db2
UH
193 license = 'gplv2+'
194 inputs = ['logic']
195 outputs = ['uart']
29ed0f4c 196 probes = [
f44d2db2
UH
197 # Allow specifying only one of the signals, e.g. if only one data
198 # direction exists (or is relevant).
29ed0f4c
UH
199 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
200 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
201 ]
f44d2db2 202 options = {
97cca21f 203 'baudrate': ['Baud rate', 115200],
f44d2db2
UH
204 'num_data_bits': ['Data bits', 8], # Valid: 5-9.
205 'parity': ['Parity', PARITY_NONE],
206 'parity_check': ['Check parity', True],
207 'num_stop_bits': ['Stop bit(s)', STOP_BITS_1],
208 'bit_order': ['Bit order', LSB_FIRST],
f44d2db2 209 # TODO: Options to invert the signal(s).
f44d2db2 210 }
e97b6ef5 211 annotations = [
97cca21f
UH
212 ['ASCII', 'Data bytes as ASCII characters'],
213 ['Decimal', 'Databytes as decimal, integer values'],
214 ['Hex', 'Data bytes in hex format'],
215 ['Octal', 'Data bytes as octal numbers'],
216 ['Bits', 'Data bytes in bit notation (sequence of 0/1 digits)'],
1bb57ab8 217 ]
f44d2db2 218
97cca21f
UH
219 def putx(self, rxtx, data):
220 self.put(self.startsample[rxtx], self.samplenum - 1, self.out_ann, data)
221
f44d2db2 222 def __init__(self, **kwargs):
f44d2db2 223 self.samplenum = 0
97cca21f
UH
224 self.frame_start = [-1, -1]
225 self.startbit = [-1, -1]
226 self.cur_data_bit = [0, 0]
227 self.databyte = [0, 0]
228 self.stopbit1 = [-1, -1]
229 self.startsample = [-1, -1]
f44d2db2
UH
230
231 # Initial state.
97cca21f 232 self.state = [WAIT_FOR_START_BIT, WAIT_FOR_START_BIT]
f44d2db2 233
97cca21f 234 self.oldbit = [None, None]
f44d2db2 235
ea90233e
UH
236 # Set protocol decoder option defaults.
237 self.baudrate = Decoder.options['baudrate'][1]
238 self.num_data_bits = Decoder.options['num_data_bits'][1]
239 self.parity = Decoder.options['parity'][1]
240 self.check_parity = Decoder.options['parity_check'][1]
241 self.num_stop_bits = Decoder.options['num_stop_bits'][1]
242 self.bit_order = Decoder.options['bit_order'][1]
243
f44d2db2 244 def start(self, metadata):
f44d2db2 245 self.samplerate = metadata['samplerate']
56202222
UH
246 self.out_proto = self.add(srd.OUTPUT_PROTO, 'uart')
247 self.out_ann = self.add(srd.OUTPUT_ANN, 'uart')
f44d2db2 248
ea90233e 249 # TODO: Override PD options, if user wants that.
f44d2db2
UH
250
251 # The width of one UART bit in number of samples.
252 self.bit_width = float(self.samplerate) / float(self.baudrate)
253
254 def report(self):
255 pass
256
257 # Return true if we reached the middle of the desired bit, false otherwise.
97cca21f 258 def reached_bit(self, rxtx, bitnum):
f44d2db2
UH
259 # bitpos is the samplenumber which is in the middle of the
260 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
261 # (if used) or the first stop bit, and so on).
97cca21f 262 bitpos = self.frame_start[rxtx] + (self.bit_width / 2.0)
f44d2db2
UH
263 bitpos += bitnum * self.bit_width
264 if self.samplenum >= bitpos:
265 return True
266 return False
267
97cca21f
UH
268 def reached_bit_last(self, rxtx, bitnum):
269 bitpos = self.frame_start[rxtx] + ((bitnum + 1) * self.bit_width)
f44d2db2
UH
270 if self.samplenum >= bitpos:
271 return True
272 return False
273
97cca21f 274 def wait_for_start_bit(self, rxtx, old_signal, signal):
f44d2db2
UH
275 # The start bit is always 0 (low). As the idle UART (and the stop bit)
276 # level is 1 (high), the beginning of a start bit is a falling edge.
277 if not (old_signal == 1 and signal == 0):
278 return
279
280 # Save the sample number where the start bit begins.
97cca21f 281 self.frame_start[rxtx] = self.samplenum
f44d2db2 282
97cca21f 283 self.state[rxtx] = GET_START_BIT
f44d2db2 284
97cca21f 285 def get_start_bit(self, rxtx, signal):
f44d2db2 286 # Skip samples until we're in the middle of the start bit.
97cca21f 287 if not self.reached_bit(rxtx, 0):
1bb57ab8 288 return
f44d2db2 289
97cca21f 290 self.startbit[rxtx] = signal
f44d2db2 291
5cc4b6a0 292 # The startbit must be 0. If not, we report an error.
97cca21f
UH
293 if self.startbit[rxtx] != 0:
294 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
295 [T_INVALID_START, rxtx, self.startbit[rxtx]])
5cc4b6a0 296 # TODO: Abort? Ignore rest of the frame?
f44d2db2 297
97cca21f
UH
298 self.cur_data_bit[rxtx] = 0
299 self.databyte[rxtx] = 0
300 self.startsample[rxtx] = -1
f44d2db2 301
97cca21f 302 self.state[rxtx] = GET_DATA_BITS
f44d2db2 303
97cca21f
UH
304 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
305 [T_START, rxtx, self.startbit[rxtx]])
306 self.put(self.frame_start[rxtx], self.samplenum, self.out_ann,
5cc4b6a0 307 [ANN_ASCII, ['Start bit', 'Start', 'S']])
f44d2db2 308
97cca21f 309 def get_data_bits(self, rxtx, signal):
f44d2db2 310 # Skip samples until we're in the middle of the desired data bit.
97cca21f 311 if not self.reached_bit(rxtx, self.cur_data_bit[rxtx] + 1):
1bb57ab8 312 return
f44d2db2
UH
313
314 # Save the sample number where the data byte starts.
97cca21f
UH
315 if self.startsample[rxtx] == -1:
316 self.startsample[rxtx] = self.samplenum
f44d2db2
UH
317
318 # Get the next data bit in LSB-first or MSB-first fashion.
319 if self.bit_order == LSB_FIRST:
97cca21f
UH
320 self.databyte[rxtx] >>= 1
321 self.databyte[rxtx] |= (signal << (self.num_data_bits - 1))
f44d2db2 322 elif self.bit_order == MSB_FIRST:
97cca21f
UH
323 self.databyte[rxtx] <<= 1
324 self.databyte[rxtx] |= (signal << 0)
f44d2db2
UH
325 else:
326 raise Exception('Invalid bit order value: %d', self.bit_order)
327
328 # Return here, unless we already received all data bits.
97cca21f
UH
329 if self.cur_data_bit[rxtx] < self.num_data_bits - 1: # TODO? Off-by-one?
330 self.cur_data_bit[rxtx] += 1
1bb57ab8 331 return
f44d2db2 332
97cca21f 333 self.state[rxtx] = GET_PARITY_BIT
f44d2db2 334
97cca21f
UH
335 self.put(self.startsample[rxtx], self.samplenum - 1, self.out_proto,
336 [T_DATA, rxtx, self.databyte[rxtx]])
f44d2db2 337
97cca21f
UH
338 s = 'RX: ' if (rxtx == RX) else 'TX: '
339 self.putx(rxtx, [ANN_ASCII, [s + chr(self.databyte[rxtx])]])
340 self.putx(rxtx, [ANN_DEC, [s + str(self.databyte[rxtx])]])
341 self.putx(rxtx, [ANN_HEX, [s + hex(self.databyte[rxtx]),
342 s + hex(self.databyte[rxtx])[2:]]])
343 self.putx(rxtx, [ANN_OCT, [s + oct(self.databyte[rxtx]),
344 s + oct(self.databyte[rxtx])[2:]]])
345 self.putx(rxtx, [ANN_BITS, [s + bin(self.databyte[rxtx]),
346 s + bin(self.databyte[rxtx])[2:]]])
f44d2db2 347
97cca21f 348 def get_parity_bit(self, rxtx, signal):
f44d2db2
UH
349 # If no parity is used/configured, skip to the next state immediately.
350 if self.parity == PARITY_NONE:
97cca21f 351 self.state[rxtx] = GET_STOP_BITS
1bb57ab8 352 return
f44d2db2
UH
353
354 # Skip samples until we're in the middle of the parity bit.
97cca21f 355 if not self.reached_bit(rxtx, self.num_data_bits + 1):
1bb57ab8 356 return
f44d2db2 357
97cca21f 358 self.paritybit[rxtx] = signal
f44d2db2 359
97cca21f 360 self.state[rxtx] = GET_STOP_BITS
f44d2db2 361
97cca21f
UH
362 if parity_ok(self.parity[rxtx], self.paritybit[rxtx],
363 self.databyte[rxtx], self.num_data_bits):
f44d2db2 364 # TODO: Fix range.
1bb57ab8 365 self.put(self.samplenum, self.samplenum, self.out_proto,
97cca21f 366 [T_PARITY_BIT, rxtx, self.paritybit[rxtx]])
1bb57ab8 367 self.put(self.samplenum, self.samplenum, self.out_ann,
5cc4b6a0 368 [ANN_ASCII, ['Parity bit', 'Parity', 'P']])
f44d2db2 369 else:
1bb57ab8 370 # TODO: Fix range.
61132abd 371 # TODO: Return expected/actual parity values.
1bb57ab8 372 self.put(self.samplenum, self.samplenum, self.out_proto,
97cca21f 373 [T_PARITY_ERROR, rxtx, (0, 1)]) # FIXME: Dummy tuple...
1bb57ab8 374 self.put(self.samplenum, self.samplenum, self.out_ann,
5cc4b6a0 375 [ANN_ASCII, ['Parity error', 'Parity err', 'PE']])
f44d2db2
UH
376
377 # TODO: Currently only supports 1 stop bit.
97cca21f 378 def get_stop_bits(self, rxtx, signal):
f44d2db2 379 # Skip samples until we're in the middle of the stop bit(s).
5b6b4f77 380 skip_parity = 0 if self.parity == PARITY_NONE else 1
97cca21f 381 if not self.reached_bit(rxtx, self.num_data_bits + 1 + skip_parity):
1bb57ab8 382 return
f44d2db2 383
97cca21f 384 self.stopbit1[rxtx] = signal
f44d2db2 385
5cc4b6a0 386 # Stop bits must be 1. If not, we report an error.
97cca21f
UH
387 if self.stopbit1[rxtx] != 1:
388 self.put(self.frame_start[rxtx], self.samplenum, self.out_proto,
389 [T_INVALID_STOP, rxtx, self.stopbit1[rxtx]])
5cc4b6a0 390 # TODO: Abort? Ignore the frame? Other?
f44d2db2 391
97cca21f 392 self.state[rxtx] = WAIT_FOR_START_BIT
f44d2db2 393
f44d2db2 394 # TODO: Fix range.
1bb57ab8 395 self.put(self.samplenum, self.samplenum, self.out_proto,
97cca21f 396 [T_STOP, rxtx, self.stopbit1[rxtx]])
1bb57ab8 397 self.put(self.samplenum, self.samplenum, self.out_ann,
5cc4b6a0 398 [ANN_ASCII, ['Stop bit', 'Stop', 'P']])
f44d2db2 399
2b9837d9 400 def decode(self, ss, es, data): # TODO
97cca21f 401 for (samplenum, (rx, tx)) in data:
f44d2db2
UH
402
403 # TODO: Start counting at 0 or 1? Increase before or after?
404 self.samplenum += 1
405
406 # First sample: Save RX/TX value.
97cca21f
UH
407 if self.oldbit[RX] == None:
408 self.oldbit[RX] = rx
409 continue
410 if self.oldbit[TX] == None:
411 self.oldbit[TX] = tx
f44d2db2
UH
412 continue
413
f44d2db2 414 # State machine.
97cca21f
UH
415 for rxtx in (RX, TX):
416 signal = rx if (rxtx == RX) else tx
417
418 if self.state[rxtx] == WAIT_FOR_START_BIT:
419 self.wait_for_start_bit(rxtx, self.oldbit[rxtx], signal)
420 elif self.state[rxtx] == GET_START_BIT:
421 self.get_start_bit(rxtx, signal)
422 elif self.state[rxtx] == GET_DATA_BITS:
423 self.get_data_bits(rxtx, signal)
424 elif self.state[rxtx] == GET_PARITY_BIT:
425 self.get_parity_bit(rxtx, signal)
426 elif self.state[rxtx] == GET_STOP_BITS:
427 self.get_stop_bits(rxtx, signal)
428 else:
429 raise Exception('Invalid state: %s' % self.state[rxtx])
430
431 # Save current RX/TX values for the next round.
432 self.oldbit[rxtx] = signal
f44d2db2 433