machine_uart.c 10 KB

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