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