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