代码拉取完成,页面将自动刷新
#include "SerialPort.h"
#include <stdio.h>
#include <fcntl.h>
#include <termio.h>
#include <unistd.h>
#include <pthread.h>
static void set_data_bit (struct termios *opt, unsigned int databit);
bool SerialPort::Open(const char *name, int baudrate, int databits, int stopbits, int parity)
{
if(isRun) {
return false;
}
_fd = open(name, O_RDWR | O_NOCTTY | O_NDELAY); //
if(_fd == -1) {
printf("open[%s] failed\n", name);
return false;
}
if(fcntl(_fd,F_SETFL,FNDELAY) < 0)//非阻塞,覆盖前面open的属性
{
printf("fcntl failed\n");
}
else{
printf("fcntl=%d\n",fcntl(_fd,F_SETFL,FNDELAY));
}
termios uart = {0};
if(tcgetattr(_fd, &uart) != 0) {
return false;
}
switch (baudrate) {
case 4800:
cfsetispeed(&uart, B4800);
cfsetospeed(&uart, B4800);
break;
case 9600:
cfsetispeed(&uart, B9600);
cfsetospeed(&uart, B9600);
break;
case 115200:
cfsetispeed(&uart, B115200);
cfsetospeed(&uart, B115200);
break;
default:
cfsetispeed(&uart, B115200);
cfsetospeed(&uart, B115200);
break;
}
uart.c_cflag |= (IXON | IXOFF | IXANY);
uart.c_cflag &= ~CSIZE;
set_data_bit(&uart, databits);
uart.c_cflag &= ~PARENB;
uart.c_cflag &= ~CSTOPB;
uart.c_cc[VTIME] = 5;
uart.c_cc[VMIN] = 1;
tcflush(_fd, TCIFLUSH);
if(tcsetattr(_fd, TCSANOW, &uart) < 0) {
return false;
}
fcntl(_fd, F_SETFL, FNDELAY);
isRun = true;
//pthread_create(&_thread, nullptr, SThreadProc, this);
return true;
}
bool SerialPort::Write(unsigned char *data, int size)
{
if(!isRun) {
return false;
}
int res = write(_fd, data, size);
return res >= 0;
}
void SerialPort::Close()
{
isRun = false;
close(_fd);
pthread_join(_thread, nullptr);
}
void SerialPort::SetDataReceiver(DataReceiver* receiver) {
this->_receiver = receiver;
}
void *SerialPort::SThreadProc(void *param) {
static_cast<SerialPort*>(param)->ThreadProc();
return nullptr;
}
void SerialPort::ThreadProc() {
unsigned char* buffer = new unsigned char[1024];
int len;
while (isRun) {
len = read(_fd, buffer, sizeof(buffer));
if(len > 0) {
if(_receiver != nullptr) {
_receiver->onSerialData(buffer, len);
}
} else {
usleep(1000);
}
}
}
int SerialPort::Read(unsigned char *buffer, int size) {
return read(_fd, buffer, size);
}
static void set_data_bit (struct termios *opt, unsigned int databit)
{
opt->c_cflag &= ~CSIZE;
switch (databit) {
case 8:
opt->c_cflag |= CS8;
break;
case 7:
opt->c_cflag |= CS7;
break;
case 6:
opt->c_cflag |= CS6;
break;
case 5:
opt->c_cflag |= CS5;
break;
default:
opt->c_cflag |= CS8;
break;
}
}
bool SerialPort::Open(const char *name, int baudrate, int databits, int stopbits, int parity) {
return false;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。