getchar.c 1.5 KB

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