]> sigrok.org Git - libsigrokdecode.git/blame - decoders/uart.py
srd: Add initial DCF77 protocol decoder.
[libsigrokdecode.git] / decoders / 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:
99# put(<startsample>, <endsample>, self.out_proto, <packet>)
100#
101# The <packet> is a list with two entries:
102# [<packet-type>, <packet-data>]
103#
104# Valid packet-type values: T_START, T_DATA, T_PARITY, T_STOP, T_INVALID_START,
105# T_INVALID_STOP, T_PARITY_ERROR
106#
107# The packet-data field has the following format and meaning:
108# - T_START: The data is the (integer) value of the start bit (0 or 1).
109# - T_DATA: The data is the (integer) value of the UART data. Valid values
110# range from 0 to 512 (as the data can be up to 9 bits in size).
111# - T_PARITY: The data is the (integer) value of the parity bit (0 or 1).
112# - T_STOP: The data is the (integer) value of the stop bit (0 or 1).
113# - T_INVALID_START: The data is the (integer) value of the start bit (0 or 1).
114# - T_INVALID_STOP: The data is the (integer) value of the stop bit (0 or 1).
115# - T_PARITY_ERROR: The data is a tuple with two entries. The first one is
116# the expected parity value, the second is the actual parity value.
117#
118# Examples:
119# [T_START, 0]
120# [T_DATA, 65]
121# [T_PARITY, 0]
122# [T_STOP, 1]
123# [T_INVALID_START, 1]
124# [T_INVALID_STOP, 0]
125# [T_PARITY_ERROR, (0, 1)]
126#
127
677d597b 128import sigrokdecode as srd
f44d2db2
UH
129
130# States
131WAIT_FOR_START_BIT = 0
132GET_START_BIT = 1
133GET_DATA_BITS = 2
134GET_PARITY_BIT = 3
135GET_STOP_BITS = 4
136
137# Parity options
138PARITY_NONE = 0
139PARITY_ODD = 1
140PARITY_EVEN = 2
141PARITY_ZERO = 3
142PARITY_ONE = 4
143
144# Stop bit options
145STOP_BITS_0_5 = 0
146STOP_BITS_1 = 1
147STOP_BITS_1_5 = 2
148STOP_BITS_2 = 3
149
150# Bit order options
151LSB_FIRST = 0
152MSB_FIRST = 1
153
1bb57ab8
UH
154# Annotation feed formats
155ANN_ASCII = 0
156ANN_DEC = 1
157ANN_HEX = 2
158ANN_OCT = 3
159ANN_BITS = 4
f44d2db2 160
61132abd
UH
161# Protocol output packet types
162T_START = 0
163T_DATA = 1
164T_PARITY = 2
165T_STOP = 3
166T_INVALID_START = 4
167T_INVALID_STOP = 5
168T_PARITY_ERROR = 6
169
f44d2db2
UH
170# Given a parity type to check (odd, even, zero, one), the value of the
171# parity bit, the value of the data, and the length of the data (5-9 bits,
172# usually 8 bits) return True if the parity is correct, False otherwise.
173# PARITY_NONE is _not_ allowed as value for 'parity_type'.
174def parity_ok(parity_type, parity_bit, data, num_data_bits):
175
176 # Handle easy cases first (parity bit is always 1 or 0).
177 if parity_type == PARITY_ZERO:
178 return parity_bit == 0
179 elif parity_type == PARITY_ONE:
180 return parity_bit == 1
181
182 # Count number of 1 (high) bits in the data (and the parity bit itself!).
183 parity = bin(data).count('1') + parity_bit
184
185 # Check for odd/even parity.
186 if parity_type == PARITY_ODD:
187 return (parity % 2) == 1
188 elif parity_type == PARITY_EVEN:
189 return (parity % 2) == 0
190 else:
191 raise Exception('Invalid parity type: %d' % parity_type)
192
677d597b 193class Decoder(srd.Decoder):
f44d2db2
UH
194 id = 'uart'
195 name = 'UART'
196 longname = 'Universal Asynchronous Receiver/Transmitter (UART)'
197 desc = 'Universal Asynchronous Receiver/Transmitter (UART)'
198 longdesc = 'TODO.'
199 author = 'Uwe Hermann'
200 email = 'uwe@hermann-uwe.de'
201 license = 'gplv2+'
202 inputs = ['logic']
203 outputs = ['uart']
29ed0f4c 204 probes = [
f44d2db2
UH
205 # Allow specifying only one of the signals, e.g. if only one data
206 # direction exists (or is relevant).
29ed0f4c
UH
207 {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'},
208 {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'},
209 ]
f44d2db2
UH
210 options = {
211 'baudrate': ['UART baud rate', 115200],
212 'num_data_bits': ['Data bits', 8], # Valid: 5-9.
213 'parity': ['Parity', PARITY_NONE],
214 'parity_check': ['Check parity', True],
215 'num_stop_bits': ['Stop bit(s)', STOP_BITS_1],
216 'bit_order': ['Bit order', LSB_FIRST],
f44d2db2
UH
217 # TODO: Options to invert the signal(s).
218 # ...
219 }
e97b6ef5 220 annotations = [
1bb57ab8 221 # ANN_ASCII
eb7082c9 222 ['ASCII', 'TODO: description'],
1bb57ab8 223 # ANN_DEC
eb7082c9 224 ['Decimal', 'TODO: description'],
1bb57ab8 225 # ANN_HEX
eb7082c9 226 ['Hex', 'TODO: description'],
1bb57ab8 227 # ANN_OCT
eb7082c9 228 ['Octal', 'TODO: description'],
1bb57ab8 229 # ANN_BITS
eb7082c9 230 ['Bits', 'TODO: description'],
1bb57ab8 231 ]
f44d2db2
UH
232
233 def __init__(self, **kwargs):
f44d2db2
UH
234 # Set defaults, can be overridden in 'start'.
235 self.baudrate = 115200
236 self.num_data_bits = 8
237 self.parity = PARITY_NONE
238 self.check_parity = True
239 self.num_stop_bits = 1
240 self.bit_order = LSB_FIRST
f44d2db2
UH
241
242 self.samplenum = 0
243 self.frame_start = -1
244 self.startbit = -1
245 self.cur_data_bit = 0
246 self.databyte = 0
247 self.stopbit1 = -1
248 self.startsample = -1
249
250 # Initial state.
251 self.staterx = WAIT_FOR_START_BIT
252
f44d2db2
UH
253 self.oldrx = None
254 self.oldtx = None
255
256 def start(self, metadata):
f44d2db2 257 self.samplerate = metadata['samplerate']
56202222
UH
258 self.out_proto = self.add(srd.OUTPUT_PROTO, 'uart')
259 self.out_ann = self.add(srd.OUTPUT_ANN, 'uart')
f44d2db2
UH
260
261 # TODO
262 ### self.baudrate = metadata['baudrate']
263 ### self.num_data_bits = metadata['num_data_bits']
264 ### self.parity = metadata['parity']
265 ### self.parity_check = metadata['parity_check']
266 ### self.num_stop_bits = metadata['num_stop_bits']
267 ### self.bit_order = metadata['bit_order']
f44d2db2
UH
268
269 # The width of one UART bit in number of samples.
270 self.bit_width = float(self.samplerate) / float(self.baudrate)
271
272 def report(self):
273 pass
274
275 # Return true if we reached the middle of the desired bit, false otherwise.
276 def reached_bit(self, bitnum):
277 # bitpos is the samplenumber which is in the middle of the
278 # specified UART bit (0 = start bit, 1..x = data, x+1 = parity bit
279 # (if used) or the first stop bit, and so on).
280 bitpos = self.frame_start + (self.bit_width / 2.0)
281 bitpos += bitnum * self.bit_width
282 if self.samplenum >= bitpos:
283 return True
284 return False
285
286 def reached_bit_last(self, bitnum):
287 bitpos = self.frame_start + ((bitnum + 1) * self.bit_width)
288 if self.samplenum >= bitpos:
289 return True
290 return False
291
292 def wait_for_start_bit(self, old_signal, signal):
293 # The start bit is always 0 (low). As the idle UART (and the stop bit)
294 # level is 1 (high), the beginning of a start bit is a falling edge.
295 if not (old_signal == 1 and signal == 0):
296 return
297
298 # Save the sample number where the start bit begins.
299 self.frame_start = self.samplenum
300
301 self.staterx = GET_START_BIT
302
303 def get_start_bit(self, signal):
304 # Skip samples until we're in the middle of the start bit.
305 if not self.reached_bit(0):
1bb57ab8 306 return
f44d2db2
UH
307
308 self.startbit = signal
309
5cc4b6a0 310 # The startbit must be 0. If not, we report an error.
f44d2db2 311 if self.startbit != 0:
5cc4b6a0 312 self.put(self.frame_start, self.samplenum, self.out_proto,
61132abd 313 [T_INVALID_START, self.startbit])
5cc4b6a0 314 # TODO: Abort? Ignore rest of the frame?
f44d2db2
UH
315
316 self.cur_data_bit = 0
317 self.databyte = 0
318 self.startsample = -1
319
320 self.staterx = GET_DATA_BITS
321
1bb57ab8 322 self.put(self.frame_start, self.samplenum, self.out_proto,
61132abd 323 [T_START, self.startbit])
1bb57ab8 324 self.put(self.frame_start, self.samplenum, self.out_ann,
5cc4b6a0 325 [ANN_ASCII, ['Start bit', 'Start', 'S']])
f44d2db2
UH
326
327 def get_data_bits(self, signal):
328 # Skip samples until we're in the middle of the desired data bit.
329 if not self.reached_bit(self.cur_data_bit + 1):
1bb57ab8 330 return
f44d2db2
UH
331
332 # Save the sample number where the data byte starts.
333 if self.startsample == -1:
334 self.startsample = self.samplenum
335
336 # Get the next data bit in LSB-first or MSB-first fashion.
337 if self.bit_order == LSB_FIRST:
338 self.databyte >>= 1
339 self.databyte |= (signal << (self.num_data_bits - 1))
340 elif self.bit_order == MSB_FIRST:
341 self.databyte <<= 1
342 self.databyte |= (signal << 0)
343 else:
344 raise Exception('Invalid bit order value: %d', self.bit_order)
345
346 # Return here, unless we already received all data bits.
347 if self.cur_data_bit < self.num_data_bits - 1: # TODO? Off-by-one?
348 self.cur_data_bit += 1
1bb57ab8 349 return
f44d2db2
UH
350
351 self.staterx = GET_PARITY_BIT
352
1bb57ab8 353 self.put(self.startsample, self.samplenum - 1, self.out_proto,
61132abd 354 [T_DATA, self.databyte])
f44d2db2 355
1bb57ab8
UH
356 self.put(self.startsample, self.samplenum - 1, self.out_ann,
357 [ANN_ASCII, [chr(self.databyte)]])
358 self.put(self.startsample, self.samplenum - 1, self.out_ann,
359 [ANN_DEC, [str(self.databyte)]])
360 self.put(self.startsample, self.samplenum - 1, self.out_ann,
361 [ANN_HEX, [hex(self.databyte), hex(self.databyte)[2:]]])
362 self.put(self.startsample, self.samplenum - 1, self.out_ann,
363 [ANN_OCT, [oct(self.databyte), oct(self.databyte)[2:]]])
364 self.put(self.startsample, self.samplenum - 1, self.out_ann,
365 [ANN_BITS, [bin(self.databyte), bin(self.databyte)[2:]]])
f44d2db2
UH
366
367 def get_parity_bit(self, signal):
368 # If no parity is used/configured, skip to the next state immediately.
369 if self.parity == PARITY_NONE:
370 self.staterx = GET_STOP_BITS
1bb57ab8 371 return
f44d2db2
UH
372
373 # Skip samples until we're in the middle of the parity bit.
374 if not self.reached_bit(self.num_data_bits + 1):
1bb57ab8 375 return
f44d2db2
UH
376
377 self.paritybit = signal
378
379 self.staterx = GET_STOP_BITS
380
381 if parity_ok(self.parity, self.paritybit, self.databyte,
382 self.num_data_bits):
f44d2db2 383 # TODO: Fix range.
1bb57ab8 384 self.put(self.samplenum, self.samplenum, self.out_proto,
61132abd 385 [T_PARITY_BIT, self.paritybit])
1bb57ab8 386 self.put(self.samplenum, self.samplenum, self.out_ann,
5cc4b6a0 387 [ANN_ASCII, ['Parity bit', 'Parity', 'P']])
f44d2db2 388 else:
1bb57ab8 389 # TODO: Fix range.
61132abd 390 # TODO: Return expected/actual parity values.
1bb57ab8 391 self.put(self.samplenum, self.samplenum, self.out_proto,
61132abd 392 [T_PARITY_ERROR, (0, 1)]) # FIXME: Dummy tuple...
1bb57ab8 393 self.put(self.samplenum, self.samplenum, self.out_ann,
5cc4b6a0 394 [ANN_ASCII, ['Parity error', 'Parity err', 'PE']])
f44d2db2
UH
395
396 # TODO: Currently only supports 1 stop bit.
397 def get_stop_bits(self, signal):
398 # Skip samples until we're in the middle of the stop bit(s).
5b6b4f77 399 skip_parity = 0 if self.parity == PARITY_NONE else 1
f44d2db2 400 if not self.reached_bit(self.num_data_bits + 1 + skip_parity):
1bb57ab8 401 return
f44d2db2
UH
402
403 self.stopbit1 = signal
404
5cc4b6a0 405 # Stop bits must be 1. If not, we report an error.
f44d2db2 406 if self.stopbit1 != 1:
5cc4b6a0 407 self.put(self.frame_start, self.samplenum, self.out_proto,
61132abd 408 [T_INVALID_STOP, self.stopbit1])
5cc4b6a0 409 # TODO: Abort? Ignore the frame? Other?
f44d2db2
UH
410
411 self.staterx = WAIT_FOR_START_BIT
412
f44d2db2 413 # TODO: Fix range.
1bb57ab8 414 self.put(self.samplenum, self.samplenum, self.out_proto,
61132abd 415 [T_STOP, self.stopbit1])
1bb57ab8 416 self.put(self.samplenum, self.samplenum, self.out_ann,
5cc4b6a0 417 [ANN_ASCII, ['Stop bit', 'Stop', 'P']])
f44d2db2 418
2b9837d9 419 def decode(self, ss, es, data): # TODO
29ed0f4c
UH
420 # for (samplenum, (rx, tx)) in data:
421 for (samplenum, (rx,)) in data:
f44d2db2
UH
422
423 # TODO: Start counting at 0 or 1? Increase before or after?
424 self.samplenum += 1
425
426 # First sample: Save RX/TX value.
427 if self.oldrx == None:
428 # Get RX/TX bit values (0/1 for low/high) of the first sample.
29ed0f4c
UH
429 self.oldrx = rx
430 # self.oldtx = tx
f44d2db2
UH
431 continue
432
f44d2db2
UH
433 # State machine.
434 if self.staterx == WAIT_FOR_START_BIT:
435 self.wait_for_start_bit(self.oldrx, rx)
436 elif self.staterx == GET_START_BIT:
1bb57ab8 437 self.get_start_bit(rx)
f44d2db2 438 elif self.staterx == GET_DATA_BITS:
1bb57ab8 439 self.get_data_bits(rx)
f44d2db2 440 elif self.staterx == GET_PARITY_BIT:
1bb57ab8 441 self.get_parity_bit(rx)
f44d2db2 442 elif self.staterx == GET_STOP_BITS:
1bb57ab8 443 self.get_stop_bits(rx)
f44d2db2
UH
444 else:
445 raise Exception('Invalid state: %s' % self.staterx)
446
447 # Save current RX/TX values for the next round.
448 self.oldrx = rx
449 # self.oldtx = tx
450
1bb57ab8
UH
451 # if proto != []:
452 # self.put(0, 0, self.out_proto, proto)
453 # if ann != []:
454 # self.put(0, 0, self.out_ann, ann)
f44d2db2 455