You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.6 KiB

2 years ago
  1. #include "uart.hpp"
  2. #include <fcntl.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <iostream>
  7. using namespace iflytop;
  8. using namespace std;
  9. Uart::Uart() {}
  10. Uart::~Uart() {}
  11. static map<string, uint32_t> s_baundmap = {
  12. {"0", 0000000}, {"50", 0000001}, {"75", 0000002}, {"110", 0000003}, //
  13. {"134", 0000004}, {"150", 0000005}, {"200", 0000006}, {"300", 0000007}, //
  14. {"600", 0000010}, {"1200", 0000011}, {"1800", 0000012}, {"2400", 0000013}, //
  15. {"4800", 0000014}, {"9600", 0000015}, {"19200", 0000016}, {"38400", 0000017}, //
  16. {"57600", 0010001}, {"115200", 0010002}, {"230400", 0010003}, {"460800", 0010004}, //
  17. {"500000", 0010005}, {"576000", 0010006}, {"921600", 0010007}, {"1000000", 0010010}, //
  18. {"1152000", 0010011}, {"1500000", 0010012}, {"2000000", 0010013}, {"2500000", 0010014}, //
  19. {"3000000", 0010015}, {"3500000", 0010016}, {"4000000", 0010017},
  20. };
  21. int Uart::open(string path) {
  22. int rc;
  23. m_name = path;
  24. m_fd = ::open(path.c_str(), O_RDWR | O_NOCTTY);
  25. if (m_fd < 0) {
  26. cout << "open " << path << " failed" << endl;
  27. return -1;
  28. }
  29. memset(&m_tty, 0, sizeof(m_tty));
  30. m_tty.c_cflag |= CLOCAL | CREAD; // 激活本地连接与接受使能
  31. m_tty.c_cflag &= ~CSIZE; // 失能数据位屏蔽
  32. m_tty.c_cflag |= CS8; // 8位数据位
  33. m_tty.c_cflag &= ~CSTOPB; // 1位停止位
  34. m_tty.c_cflag &= ~PARENB; // 无校验位
  35. m_tty.c_cc[VTIME] = 0;
  36. m_tty.c_cc[VMIN] = 0;
  37. cfsetispeed(&m_tty, B115200); // 设置输入波特率
  38. cfsetospeed(&m_tty, B115200); // 设置输出波特率
  39. tcflush(m_fd, TCIFLUSH); // 刷清未处理的输入和/或输出
  40. /* Apply attributes */
  41. rc = tcsetattr(m_fd, TCSANOW, &m_tty);
  42. if (rc) {
  43. cout << "tcsetattr failed" << endl;
  44. return -3;
  45. }
  46. return 0;
  47. }
  48. int Uart::send(char *data, int size) {
  49. int sent = 0;
  50. sent = write(m_fd, data, size);
  51. if (sent > 0) {
  52. printf("send success, data is %s\r\n", data);
  53. } else {
  54. printf("send error!\r\n");
  55. }
  56. return sent;
  57. }
  58. int Uart::receive(char *data, int size_max) {
  59. int received = 0;
  60. received = read(m_fd, data, size_max);
  61. if (received > 0) {
  62. printf("recv success,recv size is %d,data is %s\r\n", received, data);
  63. Uart::send(data, received);
  64. }
  65. return received;
  66. }
  67. int Uart::close() {
  68. ::close(m_fd);
  69. m_fd = -1;
  70. return 0;
  71. }
  72. bool Uart::flush_rx() {
  73. if (m_fd < 0) return false;
  74. int rc = tcflush(m_fd, TCIFLUSH);
  75. return rc == 0;
  76. }
  77. bool Uart::flush_tx() {
  78. if (m_fd < 0) return false;
  79. int rc = tcflush(m_fd, TCOFLUSH);
  80. return rc == 0;
  81. }