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