1 /*
2 * Copyright (c) 2017 Linaro Limited.
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/kernel.h>
8 #include <zephyr/device.h>
9 #include <zephyr/console/console.h>
10 #include <zephyr/console/tty.h>
11 #include <zephyr/drivers/uart.h>
12
13 static struct tty_serial console_serial;
14
15 static uint8_t console_rxbuf[CONFIG_CONSOLE_GETCHAR_BUFSIZE];
16 static uint8_t console_txbuf[CONFIG_CONSOLE_PUTCHAR_BUFSIZE];
17
console_write(void * dummy,const void * buf,size_t size)18 ssize_t console_write(void *dummy, const void *buf, size_t size)
19 {
20 ARG_UNUSED(dummy);
21
22 return tty_write(&console_serial, buf, size);
23 }
24
console_read(void * dummy,void * buf,size_t size)25 ssize_t console_read(void *dummy, void *buf, size_t size)
26 {
27 ARG_UNUSED(dummy);
28
29 return tty_read(&console_serial, buf, size);
30 }
31
console_putchar(char c)32 int console_putchar(char c)
33 {
34 return tty_write(&console_serial, &c, 1);
35 }
36
console_getchar(void)37 int console_getchar(void)
38 {
39 uint8_t c;
40 int res;
41
42 res = tty_read(&console_serial, &c, 1);
43 if (res < 0) {
44 return res;
45 }
46
47 return c;
48 }
49
console_init(void)50 int console_init(void)
51 {
52 const struct device *uart_dev;
53 int ret;
54
55 uart_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_console));
56 if (!device_is_ready(uart_dev)) {
57 return -ENODEV;
58 }
59
60 ret = tty_init(&console_serial, uart_dev);
61
62 if (ret) {
63 return ret;
64 }
65
66 /* Checks device driver supports for interrupt driven data transfers. */
67 if (CONFIG_CONSOLE_GETCHAR_BUFSIZE + CONFIG_CONSOLE_PUTCHAR_BUFSIZE) {
68 const struct uart_driver_api *api =
69 (const struct uart_driver_api *)uart_dev->api;
70 if (!api->irq_callback_set) {
71 return -ENOTSUP;
72 }
73 }
74
75 tty_set_tx_buf(&console_serial, console_txbuf, sizeof(console_txbuf));
76 tty_set_rx_buf(&console_serial, console_rxbuf, sizeof(console_rxbuf));
77
78 return 0;
79 }
80