machine_uart.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2018 SummerGift <zhangyuan@rt-thread.com>
  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 <string.h>
  28. #include "py/runtime.h"
  29. #include "py/mphal.h"
  30. #include "py/mperrno.h"
  31. #include "py/stream.h"
  32. #include <stdarg.h>
  33. #include "machine_uart.h"
  34. #ifdef MICROPYTHON_USING_MACHINE_UART
  35. #ifndef RT_USING_SERIAL
  36. #error "Please define the RT_USING_SERIAL on 'rtconfig.h'"
  37. #endif
  38. typedef struct _machine_uart_obj_t {
  39. mp_obj_base_t base;
  40. struct rt_serial_device *uart_device;
  41. }machine_uart_obj_t;
  42. STATIC void machine_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  43. machine_uart_obj_t *self = (machine_uart_obj_t*) self_in;
  44. mp_printf(print, "uart( device port : %s,baud_rate = %d, data_bits = %d, parity = %d, stop_bits = %d )",
  45. self->uart_device->parent.parent.name,
  46. self->uart_device->config.baud_rate,
  47. self->uart_device->config.data_bits,
  48. self->uart_device->config.parity,
  49. self->uart_device->config.stop_bits);
  50. }
  51. 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) {
  52. mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
  53. char uart_dev_name[RT_NAME_MAX];
  54. snprintf(uart_dev_name, sizeof(uart_dev_name), "uart%d", mp_obj_get_int(args[0]));
  55. struct rt_serial_device *rt_serial_device = (struct rt_serial_device *) rt_device_find(uart_dev_name);
  56. if (rt_serial_device == RT_NULL || rt_serial_device->parent.type != RT_Device_Class_Char) {
  57. mp_printf(&mp_plat_print, "ERROR: UART device %s not found!\n", uart_dev_name);
  58. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%s) doesn't exist", uart_dev_name));
  59. }
  60. rt_err_t result;
  61. result = rt_device_open((rt_device_t)rt_serial_device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX );
  62. if (result != RT_EOK)
  63. {
  64. mp_printf(&mp_plat_print, "ERROR: UART device %s can't open!\n", uart_dev_name);
  65. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%s) can't open", uart_dev_name));
  66. }
  67. // create new uart object
  68. machine_uart_obj_t *self = m_new_obj(machine_uart_obj_t);
  69. self->base.type = &machine_uart_type;
  70. self->uart_device = rt_serial_device;
  71. return (mp_obj_t) self;
  72. }
  73. /// \method init(baudrate, bits=8, parity=None, stop=1, *, timeout=1000, timeout_char=0, flow=0, read_buf_len=64)
  74. ///
  75. /// Initialise the UART bus with the given parameters:
  76. ///
  77. /// - `baudrate` is the clock rate.
  78. /// - `bits` is the number of bits per byte, 7, 8 or 9.
  79. /// - `parity` is the parity, `None`, 0 (even) or 1 (odd).
  80. /// - `stop` is the number of stop bits, 1 or 2.
  81. /// - `timeout` is the timeout in milliseconds to wait for the first character.
  82. /// - `timeout_char` is the timeout in milliseconds to wait between characters.
  83. /// - `flow` is RTS | CTS where RTS == 256, CTS == 512
  84. /// - `read_buf_len` is the character length of the read buffer (0 to disable).
  85. ///
  86. 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) {
  87. static const mp_arg_t allowed_args[] = {
  88. { MP_QSTR_baudrate, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 9600} },
  89. { MP_QSTR_bits, MP_ARG_INT, {.u_int = 8} },
  90. { MP_QSTR_parity, MP_ARG_OBJ, {.u_obj = mp_const_none} },
  91. { MP_QSTR_stop, MP_ARG_INT, {.u_int = 1} },
  92. { MP_QSTR_flow, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, // rt-thread does not support
  93. { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
  94. { MP_QSTR_timeout_char, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
  95. { MP_QSTR_read_buf_len, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 64} },
  96. };
  97. // parse args
  98. struct {
  99. mp_arg_val_t baudrate, bits, parity, stop, flow, timeout, timeout_char, read_buf_len;
  100. } args;
  101. mp_arg_parse_all(n_args, pos_args, kw_args,
  102. MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
  103. // set the UART configuration values
  104. struct rt_serial_device *uart_p = self->uart_device;
  105. struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT;
  106. // baudrate
  107. config.baud_rate = args.baudrate.u_int;
  108. // parity
  109. mp_int_t bits = args.bits.u_int;
  110. if (args.parity.u_obj == mp_const_none) {
  111. config.parity = PARITY_NONE;
  112. } else {
  113. mp_int_t parity = mp_obj_get_int(args.parity.u_obj);
  114. config.parity = (parity & 1) ? PARITY_ODD : PARITY_EVEN;
  115. //bits += 1; // STs convention has bits including parity, not all mcu
  116. }
  117. // number of bits
  118. if (bits == 8) {
  119. config.data_bits = DATA_BITS_8;
  120. } else if (bits == 9) {
  121. config.data_bits = DATA_BITS_9;
  122. } else if (bits == 7) {
  123. config.data_bits = DATA_BITS_7;
  124. } else {
  125. mp_raise_ValueError("unsupported combination of bits and parity");
  126. }
  127. // stop bits
  128. switch (args.stop.u_int) {
  129. case 1: config.stop_bits = STOP_BITS_1; break;
  130. default: config.stop_bits = STOP_BITS_2; break;
  131. }
  132. //buffer size
  133. config.bufsz = args.read_buf_len.u_int;
  134. rt_device_control((struct rt_device *) uart_p, RT_DEVICE_CTRL_CONFIG, &config);
  135. return mp_const_none;
  136. }
  137. STATIC mp_obj_t machine_uart_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
  138. return machine_uart_init_helper(args[0], n_args - 1, args + 1, kw_args);
  139. }
  140. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_uart_init_obj, 1, machine_uart_init);
  141. STATIC mp_obj_t machine_uart_deinit(mp_obj_t self_in) {
  142. return mp_const_none;
  143. }
  144. STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_deinit_obj, machine_uart_deinit);
  145. #define RETRY_TIMES 500
  146. STATIC mp_obj_t machine_uart_writechar(mp_obj_t self_in, mp_obj_t char_in) {
  147. machine_uart_obj_t *self = self_in;
  148. uint16_t data = mp_obj_get_int(char_in);
  149. rt_size_t len = 0;
  150. rt_uint32_t timeout = 0;
  151. do
  152. {
  153. len = rt_device_write((struct rt_device *)(self->uart_device), 0, &data, 1);
  154. timeout++;
  155. }
  156. while (len != 1 && timeout < RETRY_TIMES);
  157. return mp_const_none;
  158. }
  159. STATIC MP_DEFINE_CONST_FUN_OBJ_2(machine_uart_writechar_obj, machine_uart_writechar);
  160. #define UART_RX_EVENT (1 << 0)
  161. static struct rt_event event;
  162. STATIC mp_obj_t machine_uart_readchar(mp_obj_t self_in) {
  163. machine_uart_obj_t *self = self_in;
  164. rt_uint32_t e;
  165. rt_uint8_t ch;
  166. while (rt_device_read((struct rt_device *)(self->uart_device), 0, &ch, 1) != 1) {
  167. rt_event_recv(&event, UART_RX_EVENT, RT_EVENT_FLAG_AND |
  168. RT_EVENT_FLAG_CLEAR, RT_WAITING_FOREVER, &e);
  169. }
  170. return MP_OBJ_NEW_SMALL_INT(ch);
  171. }
  172. STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_readchar_obj, machine_uart_readchar);
  173. STATIC const mp_rom_map_elem_t machine_uart_locals_dict_table[] = {
  174. // instance methods
  175. { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_uart_init_obj) },
  176. { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_uart_deinit_obj) },
  177. // { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&machine_uart_any_obj) },
  178. /// \method read([nbytes])
  179. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
  180. /// \method readline()
  181. { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj)},
  182. /// \method readinto(buf[, nbytes])
  183. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
  184. /// \method write(buf)
  185. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
  186. { MP_ROM_QSTR(MP_QSTR_writechar), MP_ROM_PTR(&machine_uart_writechar_obj) },
  187. { MP_ROM_QSTR(MP_QSTR_readchar), MP_ROM_PTR(&machine_uart_readchar_obj) },
  188. // { MP_ROM_QSTR(MP_QSTR_sendbreak), MP_ROM_PTR(&pyb_uart_sendbreak_obj) },
  189. // class constants
  190. // { MP_ROM_QSTR(MP_QSTR_RTS), MP_ROM_INT(UART_HWCONTROL_RTS) },
  191. // { MP_ROM_QSTR(MP_QSTR_CTS), MP_ROM_INT(UART_HWCONTROL_CTS) },
  192. };
  193. STATIC MP_DEFINE_CONST_DICT(machine_uart_locals_dict, machine_uart_locals_dict_table);
  194. STATIC mp_uint_t machine_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) {
  195. machine_uart_obj_t *self = self_in;
  196. byte *buf = buf_in;
  197. //TODO dfs sync read
  198. //MP_RTT_NOT_IMPL_PRINT;
  199. return rt_device_read((struct rt_device *)(self->uart_device), -1, buf, size);
  200. }
  201. STATIC mp_uint_t machine_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) {
  202. machine_uart_obj_t *self = self_in;
  203. const byte *buf = buf_in;
  204. //TODO dfs sync write
  205. //MP_RTT_NOT_IMPL_PRINT;
  206. return rt_device_write((struct rt_device *)(self->uart_device), -1, buf, size);
  207. }
  208. STATIC mp_uint_t machine_uart_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode) {
  209. return NULL;
  210. }
  211. STATIC const mp_stream_p_t uart_stream_p = {
  212. .read = machine_uart_read,
  213. .write = machine_uart_write,
  214. .ioctl = machine_uart_ioctl,
  215. .is_text = false,
  216. };
  217. const mp_obj_type_t machine_uart_type = {
  218. { &mp_type_type },
  219. .name = MP_QSTR_UART,
  220. .print = machine_uart_print,
  221. .make_new = machine_uart_make_new,
  222. .getiter = mp_identity_getiter,
  223. .iternext = mp_stream_unbuffered_iter,
  224. .protocol = &uart_stream_p,
  225. .locals_dict = (mp_obj_dict_t*)&machine_uart_locals_dict,
  226. };
  227. #endif // MICROPYTHON_USING_MACHINE_UART