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