2 Star 0 Fork 0

程序员锡哥/cgutech-jni-serial

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
SerialPort.cpp 3.16 KB
一键复制 编辑 原始数据 按行查看 历史
devis 提交于 2019-07-10 10:11 . 调同红绿灯
#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;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/msgy/cgutech-jni-serial.git
git@gitee.com:msgy/cgutech-jni-serial.git
msgy
cgutech-jni-serial
cgutech-jni-serial
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385