1 /**************************************************************************//**
2 *
3 * @copyright (C) 2019 Nuvoton Technology Corp. All rights reserved.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Change Logs:
8 * Date Author Notes
9 * 2021-1-10 Wayne First version
10 *
11 ******************************************************************************/
12
13 #include <rtthread.h>
14
15 #if defined(RT_USB_DEVICE_CDC) && (defined(BSP_USING_USBD) || defined(BSP_USING_HSUSBD))
16
17 static struct rt_semaphore rx_sem;
18
uart_input(rt_device_t dev,rt_size_t size)19 static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
20 {
21 rt_err_t result = 0;
22
23 result = rt_sem_release(&rx_sem);
24 RT_ASSERT(result == RT_EOK);
25
26 return RT_EOK;
27 }
28
serial_thread_entry(void * parameter)29 static void serial_thread_entry(void *parameter)
30 {
31 rt_device_t serial = (rt_device_t)parameter;
32 char ch;
33 char szStr[64];
34 while (1)
35 {
36 while (rt_device_read(serial, -1, &ch, 1) != 1)
37 {
38 if (rt_sem_take(&rx_sem, 3 * RT_TICK_PER_SECOND) == -RT_ETIMEOUT)
39 {
40 /* output current tick */
41 rt_snprintf(szStr, sizeof(szStr), "%d\n", rt_tick_get());
42 rt_device_write(serial, 0, &szStr[0], rt_strlen(szStr));
43 continue;
44 }
45 }
46 rt_device_write(serial, 0, &ch, 1);
47 }
48 }
49
vcom_echo_init(void)50 static int vcom_echo_init(void)
51 {
52 rt_err_t result = 0;
53 rt_thread_t thread;
54 rt_device_t serial;
55
56 serial = rt_device_find("vcom");
57 if (!serial)
58 {
59 rt_kprintf("find failed!\n");
60 return -RT_ERROR;
61 }
62 result = rt_device_init(serial);
63 if (result)
64 {
65 rt_kprintf("init failed!\n");
66 return -1;
67 }
68 result = rt_device_open(serial, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX/* | RT_DEVICE_FLAG_DMA_TX */);
69 if (result)
70 {
71 rt_kprintf("open failed!\n");
72 return -1;
73 }
74
75 result = rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
76 RT_ASSERT(result == RT_EOK);
77
78 result = rt_device_set_rx_indicate(serial, uart_input);
79 RT_ASSERT(result == RT_EOK);
80
81 thread = rt_thread_create("serial", serial_thread_entry, (void *)serial, 1024, 25, 10);
82 if (thread != RT_NULL)
83 {
84 result = rt_thread_startup(thread);
85 RT_ASSERT(result == RT_EOK);
86 }
87
88 return 0;
89 }
90 INIT_APP_EXPORT(vcom_echo_init);
91
92 #endif
93