ConsoleDevice.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <errno.h>
  2. #include <fcntl.h>
  3. #include <stdio.h>
  4. #include <unistd.h>
  5. #include <signal.h>
  6. #include <AP_HAL/AP_HAL.h>
  7. #include "ConsoleDevice.h"
  8. ConsoleDevice::ConsoleDevice()
  9. {
  10. }
  11. ConsoleDevice::~ConsoleDevice()
  12. {
  13. close();
  14. }
  15. bool ConsoleDevice::close()
  16. {
  17. _closed = true;
  18. return true;
  19. }
  20. bool ConsoleDevice::open()
  21. {
  22. _rd_fd = STDIN_FILENO;
  23. _wr_fd = STDOUT_FILENO;
  24. _closed = false;
  25. if (!_set_signal_handlers()) {
  26. close();
  27. return false;
  28. }
  29. return true;
  30. }
  31. bool ConsoleDevice::_set_signal_handlers(void) const
  32. {
  33. struct sigaction sa {};
  34. sigemptyset(&sa.sa_mask);
  35. sa.sa_handler = SIG_IGN;
  36. return (sigaction(SIGTTIN, &sa, nullptr) == 0);
  37. }
  38. ssize_t ConsoleDevice::read(uint8_t *buf, uint16_t n)
  39. {
  40. if (_closed) {
  41. return -EAGAIN;
  42. }
  43. return ::read(_rd_fd, buf, n);
  44. }
  45. ssize_t ConsoleDevice::write(const uint8_t *buf, uint16_t n)
  46. {
  47. if (_closed) {
  48. return -EAGAIN;
  49. }
  50. return ::write(_wr_fd, buf, n);
  51. }
  52. void ConsoleDevice::set_blocking(bool blocking)
  53. {
  54. int rd_flags;
  55. int wr_flags;
  56. rd_flags = fcntl(_rd_fd, F_GETFL, 0);
  57. wr_flags = fcntl(_wr_fd, F_GETFL, 0);
  58. if (blocking) {
  59. rd_flags = rd_flags & ~O_NONBLOCK;
  60. wr_flags = wr_flags & ~O_NONBLOCK;
  61. } else {
  62. rd_flags = rd_flags | O_NONBLOCK;
  63. wr_flags = wr_flags | O_NONBLOCK;
  64. }
  65. if (fcntl(_rd_fd, F_SETFL, rd_flags) < 0) {
  66. ::fprintf(stderr, "Failed to set Console nonblocking %s\n", strerror(errno));
  67. }
  68. if (fcntl(_wr_fd, F_SETFL, wr_flags) < 0) {
  69. ::fprintf(stderr, "Failed to set Console nonblocking %s\n",strerror(errno));
  70. }
  71. }
  72. void ConsoleDevice::set_speed(uint32_t baudrate)
  73. {
  74. }