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.
 
 

100 lines
2.7 KiB

#include "uart.hpp"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace iflytop;
using namespace std;
static map<string, uint32_t> s_baudratemap = {
{"0", B0}, {"50", B50}, {"75", B75}, {"110", B110}, //
{"134", B134}, {"150", B150}, {"200", B200}, {"300", B300}, //
{"600", B600}, {"1200", B1200}, {"1800", B1800}, {"2400", B2400}, //
{"4800", B4800}, {"9600", B9600}, {"19200", B19200}, {"38400", B38400}, //
{"57600", B57600}, {"115200", B115200}, {"230400", B230400}, {"460800", B460800}, //
{"500000", B500000}, {"576000", B576000}, {"921600", B921600}, {"1000000", B1000000}, //
{"1152000", B1152000}, {"1500000", B1500000}, {"2000000", B2000000}, {"2500000", B2500000}, //
{"3000000", B3000000}, {"3500000", B3500000}, {"4000000", B4000000},
};
Uart::Uart() {}
Uart::~Uart() {}
int Uart::open(string path, string ratestr) {
int rc;
m_name = path;
m_fd = ::open(path.c_str(), O_RDWR | O_NOCTTY);
if (m_fd < 0) {
cout << "open " << path << " failed" << endl;
return -1;
}
if (s_baudratemap.find(ratestr) == s_baudratemap.end()) {
return -2;
}
m_rate = ratestr;
memset(&m_tty, 0, sizeof(m_tty));
m_tty.c_cflag |= CLOCAL | CREAD; // 激活本地连接与接受使能
m_tty.c_cflag &= ~CSIZE; // 失能数据位屏蔽
m_tty.c_cflag |= CS8; // 8位数据位
m_tty.c_cflag &= ~CSTOPB; // 1位停止位
m_tty.c_cflag &= ~PARENB; // 无校验位
m_tty.c_cc[VTIME] = 0;
m_tty.c_cc[VMIN] = 0;
cfsetispeed(&m_tty, s_baudratemap[ratestr]); // 设置输入波特率
cfsetospeed(&m_tty, s_baudratemap[ratestr]); // 设置输出波特率
tcflush(m_fd, TCIFLUSH); // 刷清未处理的输入和/或输出
/* Apply attributes */
rc = tcsetattr(m_fd, TCSANOW, &m_tty);
if (rc) {
cout << "tcsetattr failed" << endl;
return -3;
}
return 0;
}
int Uart::send(char *data, int size) {
int sent = 0;
sent = write(m_fd, data, size);
if (sent > 0) {
printf("send success, data is %s\r\n", data);
}
return sent;
}
int Uart::receive(char *data, int size_max) {
int received = 0;
received = read(m_fd, data, size_max);
if (received > 0) {
printf("recv success,recv size is %d,data is %s\r\n", received, data);
}
return received;
}
int Uart::close() {
::close(m_fd);
m_fd = -1;
return 0;
}
bool Uart::flush_rx() {
if (m_fd < 0) return false;
int rc = tcflush(m_fd, TCIFLUSH);
return rc == 0;
}
bool Uart::flush_tx() {
if (m_fd < 0) return false;
int rc = tcflush(m_fd, TCOFLUSH);
return rc == 0;
}