machine_uart.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2016 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdio.h>
  27. #include <stdint.h>
  28. #include <string.h>
  29. #include "driver/uart.h"
  30. #include "freertos/FreeRTOS.h"
  31. #include "py/runtime.h"
  32. #include "py/stream.h"
  33. #include "py/mperrno.h"
  34. #include "modmachine.h"
  35. typedef struct _machine_uart_obj_t {
  36. mp_obj_base_t base;
  37. uart_port_t uart_num;
  38. uint8_t bits;
  39. uint8_t parity;
  40. uint8_t stop;
  41. int8_t tx;
  42. int8_t rx;
  43. int8_t rts;
  44. int8_t cts;
  45. uint16_t timeout; // timeout waiting for first char (in ms)
  46. uint16_t timeout_char; // timeout waiting between chars (in ms)
  47. } machine_uart_obj_t;
  48. STATIC const char *_parity_name[] = {"None", "1", "0"};
  49. /******************************************************************************/
  50. // MicroPython bindings for UART
  51. STATIC void machine_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  52. machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  53. uint32_t baudrate;
  54. uart_get_baudrate(self->uart_num, &baudrate);
  55. mp_printf(print, "UART(%u, baudrate=%u, bits=%u, parity=%s, stop=%u, tx=%d, rx=%d, rts=%d, cts=%d, timeout=%u, timeout_char=%u)",
  56. self->uart_num, baudrate, self->bits, _parity_name[self->parity],
  57. self->stop, self->tx, self->rx, self->rts, self->cts, self->timeout, self->timeout_char);
  58. }
  59. STATIC void machine_uart_init_helper(machine_uart_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
  60. enum { ARG_baudrate, ARG_bits, ARG_parity, ARG_stop, ARG_tx, ARG_rx, ARG_rts, ARG_cts, ARG_timeout, ARG_timeout_char };
  61. static const mp_arg_t allowed_args[] = {
  62. { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = 0} },
  63. { MP_QSTR_bits, MP_ARG_INT, {.u_int = 0} },
  64. { MP_QSTR_parity, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
  65. { MP_QSTR_stop, MP_ARG_INT, {.u_int = 0} },
  66. { MP_QSTR_tx, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = UART_PIN_NO_CHANGE} },
  67. { MP_QSTR_rx, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = UART_PIN_NO_CHANGE} },
  68. { MP_QSTR_rts, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = UART_PIN_NO_CHANGE} },
  69. { MP_QSTR_cts, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = UART_PIN_NO_CHANGE} },
  70. { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
  71. { MP_QSTR_timeout_char, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
  72. };
  73. mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
  74. mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
  75. // wait for all data to be transmitted before changing settings
  76. uart_wait_tx_done(self->uart_num, pdMS_TO_TICKS(1000));
  77. // set baudrate
  78. uint32_t baudrate = 115200;
  79. if (args[ARG_baudrate].u_int > 0) {
  80. uart_set_baudrate(self->uart_num, args[ARG_baudrate].u_int);
  81. uart_get_baudrate(self->uart_num, &baudrate);
  82. }
  83. uart_set_pin(self->uart_num, args[ARG_tx].u_int, args[ARG_rx].u_int, args[ARG_rts].u_int, args[ARG_cts].u_int);
  84. if (args[ARG_tx].u_int != UART_PIN_NO_CHANGE) {
  85. self->tx = args[ARG_tx].u_int;
  86. }
  87. if (args[ARG_rx].u_int != UART_PIN_NO_CHANGE) {
  88. self->rx = args[ARG_rx].u_int;
  89. }
  90. if (args[ARG_rts].u_int != UART_PIN_NO_CHANGE) {
  91. self->rts = args[ARG_rts].u_int;
  92. }
  93. if (args[ARG_cts].u_int != UART_PIN_NO_CHANGE) {
  94. self->cts = args[ARG_cts].u_int;
  95. }
  96. // set data bits
  97. switch (args[ARG_bits].u_int) {
  98. case 0:
  99. break;
  100. case 5:
  101. uart_set_word_length(self->uart_num, UART_DATA_5_BITS);
  102. self->bits = 5;
  103. break;
  104. case 6:
  105. uart_set_word_length(self->uart_num, UART_DATA_6_BITS);
  106. self->bits = 6;
  107. break;
  108. case 7:
  109. uart_set_word_length(self->uart_num, UART_DATA_7_BITS);
  110. self->bits = 7;
  111. break;
  112. case 8:
  113. uart_set_word_length(self->uart_num, UART_DATA_8_BITS);
  114. self->bits = 8;
  115. break;
  116. default:
  117. mp_raise_ValueError("invalid data bits");
  118. break;
  119. }
  120. // set parity
  121. if (args[ARG_parity].u_obj != MP_OBJ_NULL) {
  122. if (args[ARG_parity].u_obj == mp_const_none) {
  123. uart_set_parity(self->uart_num, UART_PARITY_DISABLE);
  124. self->parity = 0;
  125. } else {
  126. mp_int_t parity = mp_obj_get_int(args[ARG_parity].u_obj);
  127. if (parity & 1) {
  128. uart_set_parity(self->uart_num, UART_PARITY_ODD);
  129. self->parity = 1;
  130. } else {
  131. uart_set_parity(self->uart_num, UART_PARITY_EVEN);
  132. self->parity = 2;
  133. }
  134. }
  135. }
  136. // set stop bits
  137. switch (args[ARG_stop].u_int) {
  138. // FIXME: ESP32 also supports 1.5 stop bits
  139. case 0:
  140. break;
  141. case 1:
  142. uart_set_stop_bits(self->uart_num, UART_STOP_BITS_1);
  143. self->stop = 1;
  144. break;
  145. case 2:
  146. uart_set_stop_bits(self->uart_num, UART_STOP_BITS_2);
  147. self->stop = 2;
  148. break;
  149. default:
  150. mp_raise_ValueError("invalid stop bits");
  151. break;
  152. }
  153. // set timeout
  154. self->timeout = args[ARG_timeout].u_int;
  155. // set timeout_char
  156. // make sure it is at least as long as a whole character (13 bits to be safe)
  157. self->timeout_char = args[ARG_timeout_char].u_int;
  158. uint32_t min_timeout_char = 13000 / baudrate + 1;
  159. if (self->timeout_char < min_timeout_char) {
  160. self->timeout_char = min_timeout_char;
  161. }
  162. }
  163. 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) {
  164. mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
  165. // get uart id
  166. mp_int_t uart_num = mp_obj_get_int(args[0]);
  167. if (uart_num < 0 || uart_num >= UART_NUM_MAX) {
  168. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) does not exist", uart_num));
  169. }
  170. // Attempts to use UART0 from Python has resulted in all sorts of fun errors.
  171. // FIXME: UART0 is disabled for now.
  172. if (uart_num == UART_NUM_0) {
  173. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) is disabled (dedicated to REPL)", uart_num));
  174. }
  175. // Defaults
  176. uart_config_t uartcfg = {
  177. .baud_rate = 115200,
  178. .data_bits = UART_DATA_8_BITS,
  179. .parity = UART_PARITY_DISABLE,
  180. .stop_bits = UART_STOP_BITS_1,
  181. .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
  182. .rx_flow_ctrl_thresh = 0
  183. };
  184. // create instance
  185. machine_uart_obj_t *self = m_new_obj(machine_uart_obj_t);
  186. self->base.type = &machine_uart_type;
  187. self->uart_num = uart_num;
  188. self->bits = 8;
  189. self->parity = 0;
  190. self->stop = 1;
  191. self->rts = UART_PIN_NO_CHANGE;
  192. self->cts = UART_PIN_NO_CHANGE;
  193. self->timeout = 0;
  194. self->timeout_char = 0;
  195. switch (uart_num) {
  196. case UART_NUM_0:
  197. self->rx = UART_PIN_NO_CHANGE; // GPIO 3
  198. self->tx = UART_PIN_NO_CHANGE; // GPIO 1
  199. break;
  200. case UART_NUM_1:
  201. self->rx = 9;
  202. self->tx = 10;
  203. break;
  204. case UART_NUM_2:
  205. self->rx = 16;
  206. self->tx = 17;
  207. break;
  208. }
  209. // Remove any existing configuration
  210. uart_driver_delete(self->uart_num);
  211. // init the peripheral
  212. // Setup
  213. uart_param_config(self->uart_num, &uartcfg);
  214. // RX and TX buffers are currently hardcoded at 256 bytes each (IDF minimum).
  215. uart_driver_install(uart_num, 256, 256, 0, NULL, 0);
  216. mp_map_t kw_args;
  217. mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
  218. machine_uart_init_helper(self, n_args - 1, args + 1, &kw_args);
  219. // Make sure pins are connected.
  220. uart_set_pin(self->uart_num, self->tx, self->rx, self->rts, self->cts);
  221. return MP_OBJ_FROM_PTR(self);
  222. }
  223. STATIC mp_obj_t machine_uart_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
  224. machine_uart_init_helper(args[0], n_args - 1, args + 1, kw_args);
  225. return mp_const_none;
  226. }
  227. MP_DEFINE_CONST_FUN_OBJ_KW(machine_uart_init_obj, 1, machine_uart_init);
  228. STATIC mp_obj_t machine_uart_any(mp_obj_t self_in) {
  229. machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  230. size_t rxbufsize;
  231. uart_get_buffered_data_len(self->uart_num, &rxbufsize);
  232. return MP_OBJ_NEW_SMALL_INT(rxbufsize);
  233. }
  234. STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_any_obj, machine_uart_any);
  235. STATIC const mp_rom_map_elem_t machine_uart_locals_dict_table[] = {
  236. { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_uart_init_obj) },
  237. { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&machine_uart_any_obj) },
  238. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  239. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
  240. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  241. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  242. };
  243. STATIC MP_DEFINE_CONST_DICT(machine_uart_locals_dict, machine_uart_locals_dict_table);
  244. STATIC mp_uint_t machine_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) {
  245. machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  246. // make sure we want at least 1 char
  247. if (size == 0) {
  248. return 0;
  249. }
  250. TickType_t time_to_wait;
  251. if (self->timeout == 0) {
  252. time_to_wait = 0;
  253. } else {
  254. time_to_wait = pdMS_TO_TICKS(self->timeout);
  255. }
  256. int bytes_read = uart_read_bytes(self->uart_num, buf_in, size, time_to_wait);
  257. if (bytes_read <= 0) {
  258. *errcode = MP_EAGAIN;
  259. return MP_STREAM_ERROR;
  260. }
  261. return bytes_read;
  262. }
  263. STATIC mp_uint_t machine_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) {
  264. machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
  265. int bytes_written = uart_write_bytes(self->uart_num, buf_in, size);
  266. if (bytes_written < 0) {
  267. *errcode = MP_EAGAIN;
  268. return MP_STREAM_ERROR;
  269. }
  270. // return number of bytes written
  271. return bytes_written;
  272. }
  273. STATIC mp_uint_t machine_uart_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) {
  274. machine_uart_obj_t *self = self_in;
  275. mp_uint_t ret;
  276. if (request == MP_STREAM_POLL) {
  277. mp_uint_t flags = arg;
  278. ret = 0;
  279. size_t rxbufsize;
  280. uart_get_buffered_data_len(self->uart_num, &rxbufsize);
  281. if ((flags & MP_STREAM_POLL_RD) && rxbufsize > 0) {
  282. ret |= MP_STREAM_POLL_RD;
  283. }
  284. if ((flags & MP_STREAM_POLL_WR) && 1) { // FIXME: uart_tx_any_room(self->uart_num)
  285. ret |= MP_STREAM_POLL_WR;
  286. }
  287. } else {
  288. *errcode = MP_EINVAL;
  289. ret = MP_STREAM_ERROR;
  290. }
  291. return ret;
  292. }
  293. STATIC const mp_stream_p_t uart_stream_p = {
  294. .read = machine_uart_read,
  295. .write = machine_uart_write,
  296. .ioctl = machine_uart_ioctl,
  297. .is_text = false,
  298. };
  299. const mp_obj_type_t machine_uart_type = {
  300. { &mp_type_type },
  301. .name = MP_QSTR_UART,
  302. .print = machine_uart_print,
  303. .make_new = machine_uart_make_new,
  304. .getiter = mp_identity_getiter,
  305. .iternext = mp_stream_unbuffered_iter,
  306. .protocol = &uart_stream_p,
  307. .locals_dict = (mp_obj_dict_t*)&machine_uart_locals_dict,
  308. };