1 /*
2  * This file is part of the MicroPython project, http://micropython.org/
3  *
4  * The MIT License (MIT)
5  *
6  * Copyright (c) 2020-2021 Damien P. George
7  * Copyright (c) 2021 Robert Hammelrath
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 
28 #include "py/runtime.h"
29 #include "py/stream.h"
30 #include "py/mphal.h"
31 #include "ticks.h"
32 #include "fsl_common.h"
33 #include "fsl_lpuart.h"
34 #include "fsl_iomuxc.h"
35 
36 #define DEFAULT_UART_BAUDRATE (115200)
37 #define DEFAULT_BUFFER_SIZE (256)
38 #define MIN_BUFFER_SIZE  (32)
39 #define MAX_BUFFER_SIZE  (32766)
40 
41 #define UART_INVERT_TX (1)
42 #define UART_INVERT_RX (2)
43 #define UART_INVERT_MASK (UART_INVERT_TX | UART_INVERT_RX)
44 
45 typedef struct _machine_uart_obj_t {
46     mp_obj_base_t base;
47     struct _lpuart_handle handle;
48     lpuart_config_t config;
49     LPUART_Type *lpuart;
50     uint16_t timeout;       // timeout waiting for first char (in ms)
51     uint16_t timeout_char;  // timeout waiting between chars (in ms)
52     uint8_t id;
53     uint8_t invert;
54     uint16_t tx_status;
55     uint8_t *txbuf;
56     uint16_t txbuf_len;
57     bool new;
58 } machine_uart_obj_t;
59 
60 typedef struct _iomux_table_t {
61     uint32_t muxRegister;
62     uint32_t muxMode;
63     uint32_t inputRegister;
64     uint32_t inputDaisy;
65     uint32_t configRegister;
66 } iomux_table_t;
67 
68 extern const mp_obj_type_t machine_uart_type;
69 
70 STATIC const uint8_t uart_index_table[] = MICROPY_HW_UART_INDEX;
71 STATIC LPUART_Type *uart_base_ptr_table[] = LPUART_BASE_PTRS;
72 static const iomux_table_t iomux_table_uart[] = {
73     IOMUX_TABLE_UART
74 };
75 
76 STATIC const char *_parity_name[] = {"None", "", "0", "1"};  // Is defined as 0, 2, 3
77 STATIC const char *_invert_name[] = {"None", "INV_TX", "INV_RX", "INV_TX|INV_RX"};
78 
79 #define RX (iomux_table_uart[index + 1])
80 #define TX (iomux_table_uart[index])
81 
lpuart_set_iomux(int8_t uart)82 bool lpuart_set_iomux(int8_t uart) {
83     int index = (uart - 1) * 2;
84 
85     if (TX.muxRegister != 0) {
86         IOMUXC_SetPinMux(TX.muxRegister, TX.muxMode, TX.inputRegister, TX.inputDaisy, TX.configRegister, 0U);
87         IOMUXC_SetPinConfig(TX.muxRegister, TX.muxMode, TX.inputRegister, TX.inputDaisy, TX.configRegister, 0x10B0u);
88 
89         IOMUXC_SetPinMux(RX.muxRegister, RX.muxMode, RX.inputRegister, RX.inputDaisy, RX.configRegister, 0U);
90         IOMUXC_SetPinConfig(RX.muxRegister, RX.muxMode, RX.inputRegister, RX.inputDaisy, RX.configRegister, 0x10B0u);
91         return true;
92     } else {
93         return false;
94     }
95 }
96 
UART_SrcFreq(void)97 uint32_t UART_SrcFreq(void) {
98     uint32_t freq;
99     // To make it simple, we assume default PLL and divider settings, and the
100     // only variable from application is use PLL3 source or OSC source.
101     if (CLOCK_GetMux(kCLOCK_UartMux) == 0) { // PLL3 div6 80M
102         freq = (CLOCK_GetPllFreq(kCLOCK_PllUsb1) / 6U) / (CLOCK_GetDiv(kCLOCK_UartDiv) + 1U);
103     } else {
104         freq = CLOCK_GetOscFreq() / (CLOCK_GetDiv(kCLOCK_UartDiv) + 1U);
105     }
106     return freq;
107 }
108 
LPUART_UserCallback(LPUART_Type * base,lpuart_handle_t * handle,status_t status,void * userData)109 void LPUART_UserCallback(LPUART_Type *base, lpuart_handle_t *handle, status_t status, void *userData) {
110     machine_uart_obj_t *self = userData;
111     if (kStatus_LPUART_TxIdle == status) {
112         self->tx_status = kStatus_LPUART_TxIdle;
113     }
114 
115     if (kStatus_LPUART_RxRingBufferOverrun == status) {
116         ; // Ringbuffer full, deassert RTS if flow control is enabled
117     }
118 }
119 
machine_uart_print(const mp_print_t * print,mp_obj_t self_in,mp_print_kind_t kind)120 STATIC void machine_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
121     machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
122     mp_printf(print, "UART(%u, baudrate=%u, bits=%u, parity=%s, stop=%u, "
123         "rxbuf=%d, txbuf=%d, timeout=%u, timeout_char=%u, invert=%s)",
124         self->id, self->config.baudRate_Bps, 8 - self->config.dataBitsCount,
125         _parity_name[self->config.parityMode], self->config.stopBitCount + 1,
126         self->handle.rxRingBufferSize, self->txbuf_len, self->timeout, self->timeout_char,
127         _invert_name[self->invert]);
128 }
129 
machine_uart_init_helper(machine_uart_obj_t * self,size_t n_args,const mp_obj_t * pos_args,mp_map_t * kw_args)130 STATIC mp_obj_t machine_uart_init_helper(machine_uart_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
131     enum { ARG_baudrate, ARG_bits, ARG_parity, ARG_stop,
132            ARG_timeout, ARG_timeout_char, ARG_invert, ARG_rxbuf, ARG_txbuf};
133     static const mp_arg_t allowed_args[] = {
134         { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = -1} },
135         { MP_QSTR_bits, MP_ARG_INT, {.u_int = -1} },
136         { MP_QSTR_parity, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_INT(-1)} },
137         { MP_QSTR_stop, MP_ARG_INT, {.u_int = -1} },
138         { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
139         { MP_QSTR_timeout_char, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
140         { MP_QSTR_invert, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
141         { MP_QSTR_rxbuf, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
142         { MP_QSTR_txbuf, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
143     };
144 
145     // Parse args
146     mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
147     mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
148 
149     // Set baudrate if configured.
150     if (args[ARG_baudrate].u_int > 0) {
151         self->config.baudRate_Bps = args[ARG_baudrate].u_int;
152     }
153 
154     // Set bits if configured.
155     if (args[ARG_bits].u_int > 0) {
156         self->config.dataBitsCount = 8 - args[ARG_bits].u_int;
157     }
158 
159     // Set parity if configured.
160     if (args[ARG_parity].u_obj != MP_OBJ_NEW_SMALL_INT(-1)) {
161         if (args[ARG_parity].u_obj == mp_const_none) {
162             self->config.parityMode = kLPUART_ParityDisabled;
163         } else if (mp_obj_get_int(args[ARG_parity].u_obj) & 1) {
164             self->config.parityMode = kLPUART_ParityOdd;
165         } else {
166             self->config.parityMode = kLPUART_ParityEven;
167         }
168     }
169 
170     // Set stop bits if configured.
171     if (args[ARG_stop].u_int > 0) {
172         self->config.stopBitCount = args[ARG_stop].u_int - 1;
173     }
174 
175     // Set timeout if configured.
176     if (args[ARG_timeout].u_int >= 0) {
177         self->timeout = args[ARG_timeout].u_int;
178     }
179 
180     // Set timeout_char if configured.
181     if (args[ARG_timeout_char].u_int >= 0) {
182         self->timeout_char = args[ARG_timeout_char].u_int;
183     }
184 
185     // Set line inversion if configured.
186     if (args[ARG_invert].u_int >= 0) {
187         if (args[ARG_invert].u_int & ~UART_INVERT_MASK) {
188             mp_raise_ValueError(MP_ERROR_TEXT("bad inversion mask"));
189         }
190         self->invert = args[ARG_invert].u_int;
191     }
192 
193     self->tx_status = kStatus_LPUART_TxIdle;
194     self->config.enableTx = true;
195     self->config.enableRx = true;
196 
197     // Set the RX buffer size if configured.
198     size_t rxbuf_len = DEFAULT_BUFFER_SIZE;
199     if (args[ARG_rxbuf].u_int > 0) {
200         rxbuf_len = args[ARG_rxbuf].u_int;
201         if (rxbuf_len < MIN_BUFFER_SIZE) {
202             rxbuf_len = MIN_BUFFER_SIZE;
203         } else if (rxbuf_len > MAX_BUFFER_SIZE) {
204             mp_raise_ValueError(MP_ERROR_TEXT("rxbuf too large"));
205         }
206     }
207 
208     // Set the TX buffer size if configured.
209     size_t txbuf_len = DEFAULT_BUFFER_SIZE;
210     if (args[ARG_txbuf].u_int > 0) {
211         txbuf_len = args[ARG_txbuf].u_int;
212         if (txbuf_len < MIN_BUFFER_SIZE) {
213             txbuf_len = MIN_BUFFER_SIZE;
214         } else if (txbuf_len > MAX_BUFFER_SIZE) {
215             mp_raise_ValueError(MP_ERROR_TEXT("txbuf too large"));
216         }
217     }
218 
219     // Initialise the UART peripheral if any arguments given, or it was not initialised previously.
220     if (n_args > 1 || self->new) {
221         self->new = false;
222         // may be obsolete
223         if (self->config.baudRate_Bps == 0) {
224             self->config.baudRate_Bps = DEFAULT_UART_BAUDRATE;
225         }
226 
227         // Make sure timeout_char is at least as long as a whole character (13 bits to be safe).
228         uint32_t min_timeout_char = 13000 / self->config.baudRate_Bps + 1;
229         if (self->timeout_char < min_timeout_char) {
230             self->timeout_char = min_timeout_char;
231         }
232 
233         LPUART_Init(self->lpuart, &self->config, UART_SrcFreq()); // ??
234         LPUART_TransferCreateHandle(self->lpuart, &self->handle,  LPUART_UserCallback, self);
235         uint8_t *buffer = m_new(uint8_t, rxbuf_len + 1);
236         LPUART_TransferStartRingBuffer(self->lpuart, &self->handle, buffer, rxbuf_len);
237         self->txbuf = m_new(uint8_t, txbuf_len); // Allocate the TX buffer.
238         self->txbuf_len = txbuf_len;
239 
240         // The Uart supports inverting, but not the fsl API, so it has to coded directly
241         // And it has to be done after LPUART_Init.
242         if (self->invert & UART_INVERT_RX) {
243             LPUART_EnableRx(self->lpuart, false);
244             self->lpuart->STAT |= 1 << LPUART_STAT_RXINV_SHIFT;
245             LPUART_EnableRx(self->lpuart, true);
246         }
247         if (self->invert & UART_INVERT_TX) {
248             LPUART_EnableTx(self->lpuart, false);
249             self->lpuart->CTRL |= 1 << LPUART_CTRL_TXINV_SHIFT;
250             LPUART_EnableTx(self->lpuart, true);
251         }
252         // Send long break; drop that code for a shorter break duration
253         LPUART_EnableTx(self->lpuart, false);
254         self->lpuart->STAT |= 1 << LPUART_STAT_BRK13_SHIFT;
255         LPUART_EnableTx(self->lpuart, true);
256 
257         // Allocate the TX ring buffer. Not used yet, but maybe later.
258 
259         // ringbuf_alloc(&(self->write_buffer), txbuf_len + 1);
260         // MP_STATE_PORT(rp2_uart_tx_buffer[uart_id]) = self->write_buffer.buf;
261 
262     }
263 
264     return MP_OBJ_FROM_PTR(self);
265 }
266 
machine_uart_make_new(const mp_obj_type_t * type,size_t n_args,size_t n_kw,const mp_obj_t * args)267 STATIC mp_obj_t machine_uart_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
268     mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
269 
270     // Get UART bus.
271     int uart_id = mp_obj_get_int(args[0]);
272     if (uart_id < 1 || uart_id > MICROPY_HW_UART_NUM) {
273         mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("UART(%d) doesn't exist"), uart_id);
274     }
275 
276     // Create the UART object and fill it with defaults.
277     uint8_t uart_hw_id = uart_index_table[uart_id];  // the hw uart number 1..n
278     machine_uart_obj_t *self = m_new_obj(machine_uart_obj_t);
279     self->base.type = &machine_uart_type;
280     self->id = uart_id;
281     self->lpuart = uart_base_ptr_table[uart_hw_id];
282     self->invert = false;
283     self->timeout = 1;
284     self->timeout_char = 1;
285     self->new = true;
286     LPUART_GetDefaultConfig(&self->config);
287 
288     // Configure board-specific pin MUX based on the hardware device number.
289     lpuart_set_iomux(uart_hw_id);
290 
291     mp_map_t kw_args;
292     mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
293     return machine_uart_init_helper(self, n_args - 1, args + 1, &kw_args);
294 }
295 
296 // uart.init(baud, [kwargs])
machine_uart_init(size_t n_args,const mp_obj_t * args,mp_map_t * kw_args)297 STATIC mp_obj_t machine_uart_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
298     return machine_uart_init_helper(args[0], n_args - 1, args + 1, kw_args);
299 }
300 MP_DEFINE_CONST_FUN_OBJ_KW(machine_uart_init_obj, 1, machine_uart_init);
301 
machine_uart_any(mp_obj_t self_in)302 STATIC mp_obj_t machine_uart_any(mp_obj_t self_in) {
303     machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
304     size_t count = LPUART_TransferGetRxRingBufferLength(self->lpuart, &self->handle);
305     return MP_OBJ_NEW_SMALL_INT(count);
306 }
307 STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_any_obj, machine_uart_any);
308 
machine_uart_sendbreak(mp_obj_t self_in)309 STATIC mp_obj_t machine_uart_sendbreak(mp_obj_t self_in) {
310     machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
311     self->lpuart->CTRL |= 1 << LPUART_CTRL_SBK_SHIFT; // Set SBK bit
312     self->lpuart->CTRL &= ~LPUART_CTRL_SBK_MASK; // Clear SBK bit
313     return mp_const_none;
314 }
315 STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_sendbreak_obj, machine_uart_sendbreak);
316 
317 STATIC const mp_rom_map_elem_t machine_uart_locals_dict_table[] = {
318     { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_uart_init_obj) },
319 
320     { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&machine_uart_any_obj) },
321 
322     { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
323     { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
324     { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
325     { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
326 
327     { MP_ROM_QSTR(MP_QSTR_sendbreak), MP_ROM_PTR(&machine_uart_sendbreak_obj) },
328 
329     { MP_ROM_QSTR(MP_QSTR_INV_TX), MP_ROM_INT(UART_INVERT_TX) },
330     { MP_ROM_QSTR(MP_QSTR_INV_RX), MP_ROM_INT(UART_INVERT_RX) },
331 
332 };
333 STATIC MP_DEFINE_CONST_DICT(machine_uart_locals_dict, machine_uart_locals_dict_table);
334 
machine_uart_read(mp_obj_t self_in,void * buf_in,mp_uint_t size,int * errcode)335 STATIC mp_uint_t machine_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) {
336     machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
337     uint64_t t = ticks_us64() + (uint64_t)self->timeout * 1000;
338     uint64_t timeout_char_us = (uint64_t)self->timeout_char * 1000;
339     lpuart_transfer_t xfer;
340     uint8_t *dest = buf_in;
341     size_t avail;
342     size_t nget;
343 
344     for (size_t received = 0; received < size;) {
345         // Wait for the first/next character.
346         while ((avail = LPUART_TransferGetRxRingBufferLength(self->lpuart, &self->handle)) <= 0) {
347             if (ticks_us64() > t) { // timed out
348                 if (received <= 0) {
349                     *errcode = MP_EAGAIN;
350                     return MP_STREAM_ERROR;
351                 } else {
352                     return received;
353                 }
354             }
355             MICROPY_EVENT_POLL_HOOK
356         }
357         // Get as many bytes as possible to meet the need.
358         nget = avail < (size - received) ? avail : size - received;
359         xfer.data = dest + received;
360         xfer.dataSize = nget;
361         LPUART_TransferReceiveNonBlocking(self->lpuart, &self->handle, &xfer, NULL);
362         received += nget;
363         t = ticks_us64() + timeout_char_us;
364     }
365     return size;
366 }
367 
machine_uart_write(mp_obj_t self_in,const void * buf_in,mp_uint_t size,int * errcode)368 STATIC mp_uint_t machine_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) {
369     machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
370     lpuart_transfer_t xfer;
371     uint64_t t;
372     size_t remaining = size;
373     size_t offset = 0;
374     uint8_t fifo_size = FSL_FEATURE_LPUART_FIFO_SIZEn(0);
375 
376     // First check if a previous transfer is still ongoing,
377     // then wait at least the number of remaining character times.
378     t = ticks_us64() + (uint64_t)(self->handle.txDataSize + fifo_size) * (13000000 / self->config.baudRate_Bps + 1000);
379     while (self->tx_status != kStatus_LPUART_TxIdle) {
380         if (ticks_us64() > t) { // timed out, hard error
381             *errcode = MP_ETIMEDOUT;
382             return MP_STREAM_ERROR;
383         }
384         MICROPY_EVENT_POLL_HOOK
385     }
386 
387     // Check if the first part has to be sent semi-blocking.
388     if (size > self->txbuf_len) {
389         // Send the first block.
390         xfer.data = (uint8_t *)buf_in;
391         offset = xfer.dataSize = size - self->txbuf_len;
392         self->tx_status = kStatus_LPUART_TxBusy;
393         LPUART_TransferSendNonBlocking(self->lpuart, &self->handle, &xfer);
394 
395         // Wait at least the number of character times for this chunk.
396         t = ticks_us64() + (uint64_t)xfer.dataSize * (13000000 / self->config.baudRate_Bps + 1000);
397         while (self->handle.txDataSize) {
398             // Wait for the first/next character to be sent.
399             if (ticks_us64() > t) { // timed out
400                 if (self->handle.txDataSize >= size) {
401                     *errcode = MP_ETIMEDOUT;
402                     return MP_STREAM_ERROR;
403                 } else {
404                     return size - self->handle.txDataSize;
405                 }
406             }
407             MICROPY_EVENT_POLL_HOOK
408         }
409         remaining = self->txbuf_len;
410     } else {
411         // The data fits into the tx buffer.
412         offset = 0;
413         remaining = size;
414     }
415 
416     // Send the remaining data without waiting for completion.
417     memcpy(self->txbuf, (uint8_t *)buf_in + offset, remaining);
418     xfer.data = self->txbuf;
419     xfer.dataSize = remaining;
420     self->tx_status = kStatus_LPUART_TxBusy;
421     LPUART_TransferSendNonBlocking(self->lpuart, &self->handle, &xfer);
422 
423     return size;
424 }
425 
machine_uart_ioctl(mp_obj_t self_in,mp_uint_t request,mp_uint_t arg,int * errcode)426 STATIC mp_uint_t machine_uart_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) {
427     machine_uart_obj_t *self = self_in;
428     mp_uint_t ret;
429     if (request == MP_STREAM_POLL) {
430         uintptr_t flags = arg;
431         ret = 0;
432         if (flags & MP_STREAM_POLL_RD) {
433             uint32_t count;
434             count = LPUART_TransferGetRxRingBufferLength(self->lpuart, &self->handle);
435             if (count > 0) {
436                 ret |= MP_STREAM_POLL_RD;
437             }
438         }
439         if ((flags & MP_STREAM_POLL_WR)) {
440             ret |= MP_STREAM_POLL_WR;
441         }
442     } else {
443         *errcode = MP_EINVAL;
444         ret = MP_STREAM_ERROR;
445     }
446     return ret;
447 }
448 
449 STATIC const mp_stream_p_t uart_stream_p = {
450     .read = machine_uart_read,
451     .write = machine_uart_write,
452     .ioctl = machine_uart_ioctl,
453     .is_text = false,
454 };
455 
456 const mp_obj_type_t machine_uart_type = {
457     { &mp_type_type },
458     .name = MP_QSTR_UART,
459     .print = machine_uart_print,
460     .make_new = machine_uart_make_new,
461     .getiter = mp_identity_getiter,
462     .iternext = mp_stream_unbuffered_iter,
463     .protocol = &uart_stream_p,
464     .locals_dict = (mp_obj_dict_t *)&machine_uart_locals_dict,
465 };
466