]>
Commit | Line | Data |
---|---|---|
f44d2db2 | 1 | ## |
50bd5d25 | 2 | ## This file is part of the libsigrokdecode project. |
f44d2db2 | 3 | ## |
0bb7bcf3 | 4 | ## Copyright (C) 2011-2014 Uwe Hermann <uwe@hermann-uwe.de> |
f44d2db2 UH |
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 | |
4539e9ca | 17 | ## along with this program; if not, see <http://www.gnu.org/licenses/>. |
f44d2db2 UH |
18 | ## |
19 | ||
677d597b | 20 | import sigrokdecode as srd |
5166b031 | 21 | from common.srdhelper import bitpack |
b5712ccb | 22 | from math import floor, ceil |
f44d2db2 | 23 | |
4cace3b8 | 24 | ''' |
c515eed7 | 25 | OUTPUT_PYTHON format: |
4cace3b8 | 26 | |
bf69977d UH |
27 | Packet: |
28 | [<ptype>, <rxtx>, <pdata>] | |
4cace3b8 | 29 | |
bf69977d | 30 | This is the list of <ptype>s and their respective <pdata> values: |
4cace3b8 | 31 | - 'STARTBIT': The data is the (integer) value of the start bit (0/1). |
0c7d5a56 UH |
32 | - 'DATA': This is always a tuple containing two items: |
33 | - 1st item: the (integer) value of the UART data. Valid values | |
6ffd71c1 | 34 | range from 0 to 511 (as the data can be up to 9 bits in size). |
0c7d5a56 | 35 | - 2nd item: the list of individual data bits and their ss/es numbers. |
4cace3b8 UH |
36 | - 'PARITYBIT': The data is the (integer) value of the parity bit (0/1). |
37 | - 'STOPBIT': The data is the (integer) value of the stop bit (0 or 1). | |
38 | - 'INVALID STARTBIT': The data is the (integer) value of the start bit (0/1). | |
39 | - 'INVALID STOPBIT': The data is the (integer) value of the stop bit (0/1). | |
40 | - 'PARITY ERROR': The data is a tuple with two entries. The first one is | |
41 | the expected parity value, the second is the actual parity value. | |
b025eab7 | 42 | - 'BREAK': The data is always 0. |
96170710 GS |
43 | - 'FRAME': The data is always a tuple containing two items: The (integer) |
44 | value of the UART data, and a boolean which reflects the validity of the | |
45 | UART frame. | |
77c986b3 | 46 | - 'IDLE': The data is always 0. |
4cace3b8 UH |
47 | |
48 | The <rxtx> field is 0 for RX packets, 1 for TX packets. | |
49 | ''' | |
50 | ||
97cca21f UH |
51 | # Used for differentiating between the two data directions. |
52 | RX = 0 | |
53 | TX = 1 | |
54 | ||
f44d2db2 UH |
55 | # Given a parity type to check (odd, even, zero, one), the value of the |
56 | # parity bit, the value of the data, and the length of the data (5-9 bits, | |
57 | # usually 8 bits) return True if the parity is correct, False otherwise. | |
a7fc4c34 | 58 | # 'none' is _not_ allowed as value for 'parity_type'. |
fb7a2f68 | 59 | def parity_ok(parity_type, parity_bit, data, data_bits): |
f44d2db2 | 60 | |
5ef0a979 GS |
61 | if parity_type == 'ignore': |
62 | return True | |
63 | ||
f44d2db2 | 64 | # Handle easy cases first (parity bit is always 1 or 0). |
a7fc4c34 | 65 | if parity_type == 'zero': |
f44d2db2 | 66 | return parity_bit == 0 |
a7fc4c34 | 67 | elif parity_type == 'one': |
f44d2db2 UH |
68 | return parity_bit == 1 |
69 | ||
70 | # Count number of 1 (high) bits in the data (and the parity bit itself!). | |
ac941bf9 | 71 | ones = bin(data).count('1') + parity_bit |
f44d2db2 UH |
72 | |
73 | # Check for odd/even parity. | |
a7fc4c34 | 74 | if parity_type == 'odd': |
ac941bf9 | 75 | return (ones % 2) == 1 |
a7fc4c34 | 76 | elif parity_type == 'even': |
ac941bf9 | 77 | return (ones % 2) == 0 |
f44d2db2 | 78 | |
21cda951 UH |
79 | class SamplerateError(Exception): |
80 | pass | |
81 | ||
f04964c6 UH |
82 | class ChannelError(Exception): |
83 | pass | |
84 | ||
c69e72bc UH |
85 | class Ann: |
86 | RX_DATA, TX_DATA, RX_START, TX_START, RX_PARITY_OK, TX_PARITY_OK, \ | |
87 | RX_PARITY_ERR, TX_PARITY_ERR, RX_STOP, TX_STOP, RX_WARN, TX_WARN, \ | |
88 | RX_DATA_BIT, TX_DATA_BIT, RX_BREAK, TX_BREAK, RX_PACKET, TX_PACKET = \ | |
89 | range(18) | |
90 | ||
f34113a3 UH |
91 | class Bin: |
92 | RX, TX, RXTX = range(3) | |
93 | ||
677d597b | 94 | class Decoder(srd.Decoder): |
dcd3d626 | 95 | api_version = 3 |
f44d2db2 UH |
96 | id = 'uart' |
97 | name = 'UART' | |
3d3da57d | 98 | longname = 'Universal Asynchronous Receiver/Transmitter' |
a465436e | 99 | desc = 'Asynchronous, serial bus.' |
f44d2db2 UH |
100 | license = 'gplv2+' |
101 | inputs = ['logic'] | |
102 | outputs = ['uart'] | |
d6d8a8a4 | 103 | tags = ['Embedded/industrial'] |
6a15597a | 104 | optional_channels = ( |
f44d2db2 UH |
105 | # Allow specifying only one of the signals, e.g. if only one data |
106 | # direction exists (or is relevant). | |
29ed0f4c UH |
107 | {'id': 'rx', 'name': 'RX', 'desc': 'UART receive line'}, |
108 | {'id': 'tx', 'name': 'TX', 'desc': 'UART transmit line'}, | |
da9bcbd9 | 109 | ) |
84c1c0b5 BV |
110 | options = ( |
111 | {'id': 'baudrate', 'desc': 'Baud rate', 'default': 115200}, | |
fb7a2f68 | 112 | {'id': 'data_bits', 'desc': 'Data bits', 'default': 8, |
84c1c0b5 | 113 | 'values': (5, 6, 7, 8, 9)}, |
fb7a2f68 | 114 | {'id': 'parity', 'desc': 'Parity', 'default': 'none', |
5ef0a979 | 115 | 'values': ('none', 'odd', 'even', 'zero', 'one', 'ignore')}, |
fb7a2f68 | 116 | {'id': 'stop_bits', 'desc': 'Stop bits', 'default': 1.0, |
1fc5b8a5 | 117 | 'values': (0.0, 0.5, 1.0, 1.5, 2.0)}, |
84c1c0b5 BV |
118 | {'id': 'bit_order', 'desc': 'Bit order', 'default': 'lsb-first', |
119 | 'values': ('lsb-first', 'msb-first')}, | |
ea36c198 | 120 | {'id': 'format', 'desc': 'Data format', 'default': 'hex', |
84c1c0b5 | 121 | 'values': ('ascii', 'dec', 'hex', 'oct', 'bin')}, |
1d764fd0 | 122 | {'id': 'invert_rx', 'desc': 'Invert RX', 'default': 'no', |
4eafeeef | 123 | 'values': ('yes', 'no')}, |
1d764fd0 | 124 | {'id': 'invert_tx', 'desc': 'Invert TX', 'default': 'no', |
4eafeeef | 125 | 'values': ('yes', 'no')}, |
bd50ceb3 | 126 | {'id': 'sample_point', 'desc': 'Sample point (%)', 'default': 50}, |
fb7a2f68 | 127 | {'id': 'rx_packet_delim', 'desc': 'RX packet delimiter (decimal)', |
ab0522b8 | 128 | 'default': -1}, |
fb7a2f68 | 129 | {'id': 'tx_packet_delim', 'desc': 'TX packet delimiter (decimal)', |
ab0522b8 | 130 | 'default': -1}, |
0878d4ba UH |
131 | {'id': 'rx_packet_len', 'desc': 'RX packet length', 'default': -1}, |
132 | {'id': 'tx_packet_len', 'desc': 'TX packet length', 'default': -1}, | |
84c1c0b5 | 133 | ) |
da9bcbd9 BV |
134 | annotations = ( |
135 | ('rx-data', 'RX data'), | |
136 | ('tx-data', 'TX data'), | |
e144452b UH |
137 | ('rx-start', 'RX start bit'), |
138 | ('tx-start', 'TX start bit'), | |
139 | ('rx-parity-ok', 'RX parity OK bit'), | |
140 | ('tx-parity-ok', 'TX parity OK bit'), | |
141 | ('rx-parity-err', 'RX parity error bit'), | |
142 | ('tx-parity-err', 'TX parity error bit'), | |
143 | ('rx-stop', 'RX stop bit'), | |
144 | ('tx-stop', 'TX stop bit'), | |
145 | ('rx-warning', 'RX warning'), | |
146 | ('tx-warning', 'TX warning'), | |
147 | ('rx-data-bit', 'RX data bit'), | |
148 | ('tx-data-bit', 'TX data bit'), | |
03a986ea GS |
149 | ('rx-break', 'RX break'), |
150 | ('tx-break', 'TX break'), | |
ab0522b8 UH |
151 | ('rx-packet', 'RX packet'), |
152 | ('tx-packet', 'TX packet'), | |
da9bcbd9 | 153 | ) |
2ce20a91 | 154 | annotation_rows = ( |
c69e72bc | 155 | ('rx-data-bits', 'RX bits', (Ann.RX_DATA_BIT,)), |
e144452b | 156 | ('rx-data-vals', 'RX data', (Ann.RX_DATA, Ann.RX_START, Ann.RX_PARITY_OK, Ann.RX_PARITY_ERR, Ann.RX_STOP)), |
c69e72bc | 157 | ('rx-warnings', 'RX warnings', (Ann.RX_WARN,)), |
e144452b | 158 | ('rx-breaks', 'RX breaks', (Ann.RX_BREAK,)), |
c69e72bc UH |
159 | ('rx-packets', 'RX packets', (Ann.RX_PACKET,)), |
160 | ('tx-data-bits', 'TX bits', (Ann.TX_DATA_BIT,)), | |
e144452b | 161 | ('tx-data-vals', 'TX data', (Ann.TX_DATA, Ann.TX_START, Ann.TX_PARITY_OK, Ann.TX_PARITY_ERR, Ann.TX_STOP)), |
c69e72bc | 162 | ('tx-warnings', 'TX warnings', (Ann.TX_WARN,)), |
e144452b | 163 | ('tx-breaks', 'TX breaks', (Ann.TX_BREAK,)), |
c69e72bc | 164 | ('tx-packets', 'TX packets', (Ann.TX_PACKET,)), |
2ce20a91 | 165 | ) |
0bb7bcf3 UH |
166 | binary = ( |
167 | ('rx', 'RX dump'), | |
168 | ('tx', 'TX dump'), | |
169 | ('rxtx', 'RX/TX dump'), | |
170 | ) | |
96a044da | 171 | idle_state = ['WAIT FOR START BIT', 'WAIT FOR START BIT'] |
f44d2db2 | 172 | |
97cca21f | 173 | def putx(self, rxtx, data): |
b5712ccb PA |
174 | s, halfbit = self.startsample[rxtx], self.bit_width / 2.0 |
175 | self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data) | |
15ac6604 | 176 | |
ab0522b8 UH |
177 | def putx_packet(self, rxtx, data): |
178 | s, halfbit = self.ss_packet[rxtx], self.bit_width / 2.0 | |
179 | self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_ann, data) | |
180 | ||
4aedd5b8 | 181 | def putpx(self, rxtx, data): |
b5712ccb PA |
182 | s, halfbit = self.startsample[rxtx], self.bit_width / 2.0 |
183 | self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_python, data) | |
4aedd5b8 | 184 | |
15ac6604 | 185 | def putg(self, data): |
b5712ccb PA |
186 | s, halfbit = self.samplenum, self.bit_width / 2.0 |
187 | self.put(s - floor(halfbit), s + ceil(halfbit), self.out_ann, data) | |
15ac6604 UH |
188 | |
189 | def putp(self, data): | |
b5712ccb PA |
190 | s, halfbit = self.samplenum, self.bit_width / 2.0 |
191 | self.put(s - floor(halfbit), s + ceil(halfbit), self.out_python, data) | |
97cca21f | 192 | |
03a986ea GS |
193 | def putgse(self, ss, es, data): |
194 | self.put(ss, es, self.out_ann, data) | |
195 | ||
196 | def putpse(self, ss, es, data): | |
197 | self.put(ss, es, self.out_python, data) | |
198 | ||
0bb7bcf3 | 199 | def putbin(self, rxtx, data): |
b5712ccb | 200 | s, halfbit = self.startsample[rxtx], self.bit_width / 2.0 |
2f370328 | 201 | self.put(s - floor(halfbit), self.samplenum + ceil(halfbit), self.out_binary, data) |
0bb7bcf3 | 202 | |
92b7b49f | 203 | def __init__(self): |
10aeb8ea GS |
204 | self.reset() |
205 | ||
206 | def reset(self): | |
f372d597 | 207 | self.samplerate = None |
97cca21f | 208 | self.frame_start = [-1, -1] |
96170710 | 209 | self.frame_valid = [None, None] |
e556e116 | 210 | self.cur_frame_bit = [None, None] |
97cca21f UH |
211 | self.startbit = [-1, -1] |
212 | self.cur_data_bit = [0, 0] | |
e9a3c933 | 213 | self.datavalue = [0, 0] |
1ccef461 | 214 | self.paritybit = [-1, -1] |
1fc5b8a5 | 215 | self.stopbits = [[], []] |
97cca21f | 216 | self.startsample = [-1, -1] |
2b716038 | 217 | self.state = ['WAIT FOR START BIT', 'WAIT FOR START BIT'] |
4aedd5b8 | 218 | self.databits = [[], []] |
03a986ea | 219 | self.break_start = [None, None] |
ab0522b8 UH |
220 | self.packet_cache = [[], []] |
221 | self.ss_packet, self.es_packet = [None, None], [None, None] | |
d97440cc | 222 | self.idle_start = [None, None] |
f44d2db2 | 223 | |
f372d597 | 224 | def start(self): |
c515eed7 | 225 | self.out_python = self.register(srd.OUTPUT_PYTHON) |
2f370328 | 226 | self.out_binary = self.register(srd.OUTPUT_BINARY) |
be465111 | 227 | self.out_ann = self.register(srd.OUTPUT_ANN) |
fb7a2f68 | 228 | self.bw = (self.options['data_bits'] + 7) // 8 |
f44d2db2 | 229 | |
f372d597 BV |
230 | def metadata(self, key, value): |
231 | if key == srd.SRD_CONF_SAMPLERATE: | |
35b380b1 | 232 | self.samplerate = value |
f372d597 BV |
233 | # The width of one UART bit in number of samples. |
234 | self.bit_width = float(self.samplerate) / float(self.options['baudrate']) | |
f44d2db2 | 235 | |
dcd3d626 | 236 | def get_sample_point(self, rxtx, bitnum): |
0b83932c | 237 | # Determine absolute sample number of a bit slot's sample point. |
bd50ceb3 GS |
238 | # Counts for UART bits start from 0 (0 = start bit, 1..x = data, |
239 | # x+1 = parity bit (if used) or the first stop bit, and so on). | |
3d2d91e0 | 240 | # Accept a position in the range of 1-99% of the full bit width. |
bd50ceb3 GS |
241 | # Assume 50% for invalid input specs for backwards compatibility. |
242 | perc = self.options['sample_point'] or 50 | |
243 | if not perc or perc not in range(1, 100): | |
244 | perc = 50 | |
3d2d91e0 GS |
245 | perc /= 100.0 |
246 | bitpos = (self.bit_width - 1) * perc | |
bd50ceb3 | 247 | bitpos += self.frame_start[rxtx] |
f44d2db2 | 248 | bitpos += bitnum * self.bit_width |
dcd3d626 GS |
249 | return bitpos |
250 | ||
dcd3d626 | 251 | def wait_for_start_bit(self, rxtx, signal): |
f44d2db2 | 252 | # Save the sample number where the start bit begins. |
97cca21f | 253 | self.frame_start[rxtx] = self.samplenum |
96170710 | 254 | self.frame_valid[rxtx] = True |
e556e116 | 255 | self.cur_frame_bit[rxtx] = 0 |
f44d2db2 | 256 | |
42d4d65c | 257 | self.advance_state(rxtx, signal) |
f44d2db2 | 258 | |
97cca21f | 259 | def get_start_bit(self, rxtx, signal): |
97cca21f | 260 | self.startbit[rxtx] = signal |
e556e116 | 261 | self.cur_frame_bit[rxtx] += 1 |
f44d2db2 | 262 | |
711d0602 GS |
263 | # The startbit must be 0. If not, we report an error and wait |
264 | # for the next start bit (assuming this one was spurious). | |
97cca21f | 265 | if self.startbit[rxtx] != 0: |
15ac6604 | 266 | self.putp(['INVALID STARTBIT', rxtx, self.startbit[rxtx]]) |
c69e72bc | 267 | self.putg([Ann.RX_WARN + rxtx, ['Frame error', 'Frame err', 'FE']]) |
96170710 GS |
268 | self.frame_valid[rxtx] = False |
269 | es = self.samplenum + ceil(self.bit_width / 2.0) | |
270 | self.putpse(self.frame_start[rxtx], es, ['FRAME', rxtx, | |
271 | (self.datavalue[rxtx], self.frame_valid[rxtx])]) | |
42d4d65c | 272 | self.advance_state(rxtx, signal, fatal = True, idle = es) |
711d0602 | 273 | return |
f44d2db2 | 274 | |
1fc5b8a5 | 275 | # Reset internal state for the pending UART frame. |
97cca21f | 276 | self.cur_data_bit[rxtx] = 0 |
e9a3c933 | 277 | self.datavalue[rxtx] = 0 |
1fc5b8a5 GS |
278 | self.paritybit[rxtx] = -1 |
279 | self.stopbits[rxtx].clear() | |
97cca21f | 280 | self.startsample[rxtx] = -1 |
1fc5b8a5 | 281 | self.databits[rxtx].clear() |
f44d2db2 | 282 | |
15ac6604 | 283 | self.putp(['STARTBIT', rxtx, self.startbit[rxtx]]) |
c69e72bc | 284 | self.putg([Ann.RX_START + rxtx, ['Start bit', 'Start', 'S']]) |
f44d2db2 | 285 | |
42d4d65c | 286 | self.advance_state(rxtx, signal) |
4bb42a91 | 287 | |
ab0522b8 | 288 | def handle_packet(self, rxtx): |
0878d4ba | 289 | d = 'rx' if (rxtx == RX) else 'tx' |
fb7a2f68 | 290 | delim = self.options[d + '_packet_delim'] |
0878d4ba UH |
291 | plen = self.options[d + '_packet_len'] |
292 | if delim == -1 and plen == -1: | |
ab0522b8 UH |
293 | return |
294 | ||
0878d4ba UH |
295 | # Cache data values until we see the delimiter and/or the specified |
296 | # packet length has been reached (whichever happens first). | |
ab0522b8 UH |
297 | if len(self.packet_cache[rxtx]) == 0: |
298 | self.ss_packet[rxtx] = self.startsample[rxtx] | |
299 | self.packet_cache[rxtx].append(self.datavalue[rxtx]) | |
0878d4ba | 300 | if self.datavalue[rxtx] == delim or len(self.packet_cache[rxtx]) == plen: |
ab0522b8 UH |
301 | self.es_packet[rxtx] = self.samplenum |
302 | s = '' | |
303 | for b in self.packet_cache[rxtx]: | |
304 | s += self.format_value(b) | |
305 | if self.options['format'] != 'ascii': | |
306 | s += ' ' | |
307 | if self.options['format'] != 'ascii' and s[-1] == ' ': | |
308 | s = s[:-1] # Drop trailing space. | |
c69e72bc | 309 | self.putx_packet(rxtx, [Ann.RX_PACKET + rxtx, [s]]) |
ab0522b8 UH |
310 | self.packet_cache[rxtx] = [] |
311 | ||
97cca21f | 312 | def get_data_bits(self, rxtx, signal): |
15ac6604 | 313 | # Save the sample number of the middle of the first data bit. |
97cca21f UH |
314 | if self.startsample[rxtx] == -1: |
315 | self.startsample[rxtx] = self.samplenum | |
f44d2db2 | 316 | |
c69e72bc | 317 | self.putg([Ann.RX_DATA_BIT + rxtx, ['%d' % signal]]) |
4aedd5b8 UH |
318 | |
319 | # Store individual data bits and their start/end samplenumbers. | |
320 | s, halfbit = self.samplenum, int(self.bit_width / 2) | |
321 | self.databits[rxtx].append([signal, s - halfbit, s + halfbit]) | |
e556e116 | 322 | self.cur_frame_bit[rxtx] += 1 |
4aedd5b8 | 323 | |
f44d2db2 | 324 | # Return here, unless we already received all data bits. |
5e3c79fd | 325 | self.cur_data_bit[rxtx] += 1 |
fb7a2f68 | 326 | if self.cur_data_bit[rxtx] < self.options['data_bits']: |
1bb57ab8 | 327 | return |
f44d2db2 | 328 | |
5166b031 GS |
329 | # Convert accumulated data bits to a data value. |
330 | bits = [b[0] for b in self.databits[rxtx]] | |
331 | if self.options['bit_order'] == 'msb-first': | |
332 | bits.reverse() | |
333 | self.datavalue[rxtx] = bitpack(bits) | |
7cf698c5 | 334 | self.putpx(rxtx, ['DATA', rxtx, |
e9a3c933 | 335 | (self.datavalue[rxtx], self.databits[rxtx])]) |
f44d2db2 | 336 | |
6ffd71c1 GS |
337 | b = self.datavalue[rxtx] |
338 | formatted = self.format_value(b) | |
339 | if formatted is not None: | |
340 | self.putx(rxtx, [rxtx, [formatted]]) | |
f44d2db2 | 341 | |
98b89139 | 342 | bdata = b.to_bytes(self.bw, byteorder='big') |
f34113a3 UH |
343 | self.putbin(rxtx, [Bin.RX + rxtx, bdata]) |
344 | self.putbin(rxtx, [Bin.RXTX, bdata]) | |
0bb7bcf3 | 345 | |
ab0522b8 UH |
346 | self.handle_packet(rxtx) |
347 | ||
c1fc50b1 | 348 | self.databits[rxtx] = [] |
4aedd5b8 | 349 | |
42d4d65c | 350 | self.advance_state(rxtx, signal) |
4bb42a91 | 351 | |
6ffd71c1 GS |
352 | def format_value(self, v): |
353 | # Format value 'v' according to configured options. | |
354 | # Reflects the user selected kind of representation, as well as | |
355 | # the number of data bits in the UART frames. | |
356 | ||
fb7a2f68 | 357 | fmt, bits = self.options['format'], self.options['data_bits'] |
6ffd71c1 GS |
358 | |
359 | # Assume "is printable" for values from 32 to including 126, | |
360 | # below 32 is "control" and thus not printable, above 127 is | |
361 | # "not ASCII" in its strict sense, 127 (DEL) is not printable, | |
362 | # fall back to hex representation for non-printables. | |
363 | if fmt == 'ascii': | |
364 | if v in range(32, 126 + 1): | |
365 | return chr(v) | |
366 | hexfmt = "[{:02X}]" if bits <= 8 else "[{:03X}]" | |
367 | return hexfmt.format(v) | |
368 | ||
369 | # Mere number to text conversion without prefix and padding | |
370 | # for the "decimal" output format. | |
371 | if fmt == 'dec': | |
372 | return "{:d}".format(v) | |
373 | ||
374 | # Padding with leading zeroes for hex/oct/bin formats, but | |
375 | # without a prefix for density -- since the format is user | |
376 | # specified, there is no ambiguity. | |
377 | if fmt == 'hex': | |
378 | digits = (bits + 4 - 1) // 4 | |
379 | fmtchar = "X" | |
380 | elif fmt == 'oct': | |
381 | digits = (bits + 3 - 1) // 3 | |
382 | fmtchar = "o" | |
383 | elif fmt == 'bin': | |
384 | digits = bits | |
385 | fmtchar = "b" | |
386 | else: | |
387 | fmtchar = None | |
388 | if fmtchar is not None: | |
389 | fmt = "{{:0{:d}{:s}}}".format(digits, fmtchar) | |
390 | return fmt.format(v) | |
391 | ||
392 | return None | |
393 | ||
97cca21f | 394 | def get_parity_bit(self, rxtx, signal): |
97cca21f | 395 | self.paritybit[rxtx] = signal |
e556e116 | 396 | self.cur_frame_bit[rxtx] += 1 |
f44d2db2 | 397 | |
fb7a2f68 UH |
398 | if parity_ok(self.options['parity'], self.paritybit[rxtx], |
399 | self.datavalue[rxtx], self.options['data_bits']): | |
15ac6604 | 400 | self.putp(['PARITYBIT', rxtx, self.paritybit[rxtx]]) |
c69e72bc | 401 | self.putg([Ann.RX_PARITY_OK + rxtx, ['Parity bit', 'Parity', 'P']]) |
f44d2db2 | 402 | else: |
61132abd | 403 | # TODO: Return expected/actual parity values. |
15ac6604 | 404 | self.putp(['PARITY ERROR', rxtx, (0, 1)]) # FIXME: Dummy tuple... |
c69e72bc | 405 | self.putg([Ann.RX_PARITY_ERR + rxtx, ['Parity error', 'Parity err', 'PE']]) |
96170710 | 406 | self.frame_valid[rxtx] = False |
f44d2db2 | 407 | |
42d4d65c | 408 | self.advance_state(rxtx, signal) |
4bb42a91 | 409 | |
97cca21f | 410 | def get_stop_bits(self, rxtx, signal): |
1fc5b8a5 | 411 | self.stopbits[rxtx].append(signal) |
e556e116 | 412 | self.cur_frame_bit[rxtx] += 1 |
f44d2db2 | 413 | |
5cc4b6a0 | 414 | # Stop bits must be 1. If not, we report an error. |
1fc5b8a5 GS |
415 | if signal != 1: |
416 | self.putp(['INVALID STOPBIT', rxtx, signal]) | |
c69e72bc | 417 | self.putg([Ann.RX_WARN + rxtx, ['Frame error', 'Frame err', 'FE']]) |
96170710 | 418 | self.frame_valid[rxtx] = False |
f44d2db2 | 419 | |
1fc5b8a5 | 420 | self.putp(['STOPBIT', rxtx, signal]) |
b2ddb8ee | 421 | self.putg([Ann.RX_STOP + rxtx, ['Stop bit', 'Stop', 'T']]) |
f44d2db2 | 422 | |
1fc5b8a5 GS |
423 | # Postprocess the UART frame after all STOP bits were seen. |
424 | if len(self.stopbits[rxtx]) < self.options['stop_bits']: | |
425 | return | |
42d4d65c GS |
426 | self.advance_state(rxtx, signal) |
427 | ||
428 | def advance_state(self, rxtx, signal = None, fatal = False, idle = None): | |
429 | # Advances the protocol decoder's internal state for all regular | |
430 | # UART frame inspection. Deals with either edges, sample points, | |
431 | # or other .wait() conditions. Also gracefully handles extreme | |
432 | # undersampling. Each turn takes one .wait() call which in turn | |
433 | # corresponds to at least one sample. That is why as many state | |
434 | # transitions are done here as required within a single call. | |
435 | frame_end = self.frame_start[rxtx] + self.frame_len_sample_count | |
436 | if idle is not None: | |
437 | # When requested by the caller, start another (potential) | |
438 | # IDLE period after the caller specified position. | |
439 | self.idle_start[rxtx] = idle | |
440 | if fatal: | |
441 | # When requested by the caller, don't advance to the next | |
442 | # UART frame's field, but to the start of the next START bit | |
443 | # instead. | |
444 | self.state[rxtx] = 'WAIT FOR START BIT' | |
445 | return | |
446 | # Advance to the next UART frame's field that we expect. Cope | |
447 | # with absence of optional fields. Force scan for next IDLE | |
448 | # after the (optional) STOP bit field, so that callers need | |
449 | # not deal with optional field presence. Also handles the cases | |
450 | # where the decoder navigates to edges which are not strictly | |
451 | # a field's sampling point. | |
452 | if self.state[rxtx] == 'WAIT FOR START BIT': | |
453 | self.state[rxtx] = 'GET START BIT' | |
454 | return | |
455 | if self.state[rxtx] == 'GET START BIT': | |
456 | self.state[rxtx] = 'GET DATA BITS' | |
457 | return | |
458 | if self.state[rxtx] == 'GET DATA BITS': | |
459 | self.state[rxtx] = 'GET PARITY BIT' | |
460 | if self.options['parity'] != 'none': | |
461 | return | |
462 | # FALLTHROUGH | |
463 | if self.state[rxtx] == 'GET PARITY BIT': | |
464 | self.state[rxtx] = 'GET STOP BITS' | |
465 | if self.options['stop_bits']: | |
466 | return | |
467 | # FALLTHROUGH | |
468 | if self.state[rxtx] == 'GET STOP BITS': | |
469 | # Postprocess the previously received UART frame. Advance | |
470 | # the read position to after the frame's last bit time. So | |
471 | # that the start of the next START bit won't fall into the | |
472 | # end of the previously received UART frame. This improves | |
473 | # robustness in the presence of glitchy input data. | |
474 | ss = self.frame_start[rxtx] | |
475 | es = self.samplenum + ceil(self.bit_width / 2.0) | |
476 | self.handle_frame(rxtx, ss, es) | |
477 | self.state[rxtx] = 'WAIT FOR START BIT' | |
478 | self.idle_start[rxtx] = frame_end | |
479 | return | |
480 | # Unhandled state, actually a programming error. Emit diagnostics? | |
481 | self.state[rxtx] = 'WAIT FOR START BIT' | |
482 | ||
483 | def handle_frame(self, rxtx, ss, es): | |
96170710 | 484 | # Pass the complete UART frame to upper layers. |
42d4d65c | 485 | self.putpse(ss, es, ['FRAME', rxtx, |
96170710 GS |
486 | (self.datavalue[rxtx], self.frame_valid[rxtx])]) |
487 | ||
42d4d65c GS |
488 | def handle_idle(self, rxtx, ss, es): |
489 | self.putpse(ss, es, ['IDLE', rxtx, 0]) | |
4bb42a91 | 490 | |
42d4d65c GS |
491 | def handle_break(self, rxtx, ss, es): |
492 | self.putpse(ss, es, ['BREAK', rxtx, 0]) | |
493 | self.putgse(ss, es, [Ann.RX_BREAK + rxtx, | |
494 | ['Break condition', 'Break', 'Brk', 'B']]) | |
03a986ea GS |
495 | self.state[rxtx] = 'WAIT FOR START BIT' |
496 | ||
dcd3d626 | 497 | def get_wait_cond(self, rxtx, inv): |
0b83932c UH |
498 | # Return condititions that are suitable for Decoder.wait(). Those |
499 | # conditions either match the falling edge of the START bit, or | |
500 | # the sample point of the next bit time. | |
dcd3d626 GS |
501 | state = self.state[rxtx] |
502 | if state == 'WAIT FOR START BIT': | |
503 | return {rxtx: 'r' if inv else 'f'} | |
e556e116 GS |
504 | if state in ('GET START BIT', 'GET DATA BITS', |
505 | 'GET PARITY BIT', 'GET STOP BITS'): | |
506 | bitnum = self.cur_frame_bit[rxtx] | |
1fc5b8a5 | 507 | # TODO: Currently does not support half STOP bits. |
e556e116 GS |
508 | want_num = ceil(self.get_sample_point(rxtx, bitnum)) |
509 | return {'skip': want_num - self.samplenum} | |
dcd3d626 | 510 | |
d97440cc GS |
511 | def get_idle_cond(self, rxtx, inv): |
512 | # Return a condition that corresponds to the (expected) end of | |
513 | # the next frame, assuming that it will be an "idle frame" | |
514 | # (constant high input level for the frame's length). | |
515 | if self.idle_start[rxtx] is None: | |
516 | return None | |
517 | end_of_frame = self.idle_start[rxtx] + self.frame_len_sample_count | |
518 | if end_of_frame < self.samplenum: | |
519 | return None | |
520 | return {'skip': end_of_frame - self.samplenum} | |
521 | ||
0de2810f | 522 | def inspect_sample(self, rxtx, signal, inv): |
0b83932c | 523 | # Inspect a sample returned by .wait() for the specified UART line. |
0de2810f GS |
524 | if inv: |
525 | signal = not signal | |
526 | ||
527 | state = self.state[rxtx] | |
528 | if state == 'WAIT FOR START BIT': | |
529 | self.wait_for_start_bit(rxtx, signal) | |
530 | elif state == 'GET START BIT': | |
531 | self.get_start_bit(rxtx, signal) | |
532 | elif state == 'GET DATA BITS': | |
533 | self.get_data_bits(rxtx, signal) | |
534 | elif state == 'GET PARITY BIT': | |
535 | self.get_parity_bit(rxtx, signal) | |
536 | elif state == 'GET STOP BITS': | |
537 | self.get_stop_bits(rxtx, signal) | |
538 | ||
03a986ea GS |
539 | def inspect_edge(self, rxtx, signal, inv): |
540 | # Inspect edges, independently from traffic, to detect break conditions. | |
541 | if inv: | |
542 | signal = not signal | |
543 | if not signal: | |
544 | # Signal went low. Start another interval. | |
545 | self.break_start[rxtx] = self.samplenum | |
546 | return | |
547 | # Signal went high. Was there an extended period with low signal? | |
548 | if self.break_start[rxtx] is None: | |
549 | return | |
550 | diff = self.samplenum - self.break_start[rxtx] | |
551 | if diff >= self.break_min_sample_count: | |
42d4d65c GS |
552 | ss, es = self.frame_start[rxtx], self.samplenum |
553 | self.handle_break(rxtx, ss, es) | |
03a986ea GS |
554 | self.break_start[rxtx] = None |
555 | ||
d97440cc GS |
556 | def inspect_idle(self, rxtx, signal, inv): |
557 | # Check each edge and each period of stable input (either level). | |
558 | # Can derive the "idle frame period has passed" condition. | |
559 | if inv: | |
560 | signal = not signal | |
561 | if not signal: | |
562 | # Low input, cease inspection. | |
563 | self.idle_start[rxtx] = None | |
564 | return | |
565 | # High input, either just reached, or still stable. | |
566 | if self.idle_start[rxtx] is None: | |
567 | self.idle_start[rxtx] = self.samplenum | |
568 | diff = self.samplenum - self.idle_start[rxtx] | |
569 | if diff < self.frame_len_sample_count: | |
570 | return | |
571 | ss, es = self.idle_start[rxtx], self.samplenum | |
42d4d65c GS |
572 | self.handle_idle(rxtx, ss, es) |
573 | self.idle_start[rxtx] = es | |
d97440cc | 574 | |
dcd3d626 | 575 | def decode(self): |
21cda951 UH |
576 | if not self.samplerate: |
577 | raise SamplerateError('Cannot decode without samplerate.') | |
2fcd7c22 | 578 | |
dcd3d626 | 579 | has_pin = [self.has_channel(ch) for ch in (RX, TX)] |
81bb8e84 GS |
580 | if not True in has_pin: |
581 | raise ChannelError('Need at least one of TX or RX pins.') | |
dcd3d626 GS |
582 | |
583 | opt = self.options | |
584 | inv = [opt['invert_rx'] == 'yes', opt['invert_tx'] == 'yes'] | |
03a986ea GS |
585 | cond_data_idx = [None] * len(has_pin) |
586 | ||
587 | # Determine the number of samples for a complete frame's time span. | |
588 | # A period of low signal (at least) that long is a break condition. | |
589 | frame_samples = 1 # START | |
fb7a2f68 UH |
590 | frame_samples += self.options['data_bits'] |
591 | frame_samples += 0 if self.options['parity'] == 'none' else 1 | |
592 | frame_samples += self.options['stop_bits'] | |
03a986ea | 593 | frame_samples *= self.bit_width |
d97440cc GS |
594 | self.frame_len_sample_count = ceil(frame_samples) |
595 | self.break_min_sample_count = self.frame_len_sample_count | |
03a986ea | 596 | cond_edge_idx = [None] * len(has_pin) |
d97440cc | 597 | cond_idle_idx = [None] * len(has_pin) |
dcd3d626 GS |
598 | |
599 | while True: | |
600 | conds = [] | |
601 | if has_pin[RX]: | |
03a986ea | 602 | cond_data_idx[RX] = len(conds) |
dcd3d626 | 603 | conds.append(self.get_wait_cond(RX, inv[RX])) |
03a986ea GS |
604 | cond_edge_idx[RX] = len(conds) |
605 | conds.append({RX: 'e'}) | |
d97440cc GS |
606 | cond_idle_idx[RX] = None |
607 | idle_cond = self.get_idle_cond(RX, inv[RX]) | |
608 | if idle_cond: | |
609 | cond_idle_idx[RX] = len(conds) | |
610 | conds.append(idle_cond) | |
dcd3d626 | 611 | if has_pin[TX]: |
03a986ea | 612 | cond_data_idx[TX] = len(conds) |
dcd3d626 | 613 | conds.append(self.get_wait_cond(TX, inv[TX])) |
03a986ea GS |
614 | cond_edge_idx[TX] = len(conds) |
615 | conds.append({TX: 'e'}) | |
d97440cc GS |
616 | cond_idle_idx[TX] = None |
617 | idle_cond = self.get_idle_cond(TX, inv[TX]) | |
618 | if idle_cond: | |
619 | cond_idle_idx[TX] = len(conds) | |
620 | conds.append(idle_cond) | |
dcd3d626 | 621 | (rx, tx) = self.wait(conds) |
03a986ea | 622 | if cond_data_idx[RX] is not None and self.matched[cond_data_idx[RX]]: |
0de2810f | 623 | self.inspect_sample(RX, rx, inv[RX]) |
03a986ea GS |
624 | if cond_edge_idx[RX] is not None and self.matched[cond_edge_idx[RX]]: |
625 | self.inspect_edge(RX, rx, inv[RX]) | |
d97440cc GS |
626 | self.inspect_idle(RX, rx, inv[RX]) |
627 | if cond_idle_idx[RX] is not None and self.matched[cond_idle_idx[RX]]: | |
628 | self.inspect_idle(RX, rx, inv[RX]) | |
03a986ea | 629 | if cond_data_idx[TX] is not None and self.matched[cond_data_idx[TX]]: |
0de2810f | 630 | self.inspect_sample(TX, tx, inv[TX]) |
03a986ea GS |
631 | if cond_edge_idx[TX] is not None and self.matched[cond_edge_idx[TX]]: |
632 | self.inspect_edge(TX, tx, inv[TX]) | |
d97440cc GS |
633 | self.inspect_idle(TX, tx, inv[TX]) |
634 | if cond_idle_idx[TX] is not None and self.matched[cond_idle_idx[TX]]: | |
635 | self.inspect_idle(TX, tx, inv[TX]) |