c++定义hpp文件
c++ 定义hpp文件,注意事项
方法定义实现必须放在类中,否则会出现重复定义情况。
#ifndef MAVLINK_DATALINK_SERIALPORT_HPP
#define MAVLINK_DATALINK_SERIALPORT_HPP
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include "mavlink.h"
using namespace std;
class SerialPort {
public:
SerialPort(string uart_name, speed_t baudrate){
uartName = uart_name;
speedBaud = baudrate;
}
public:
int open_serial_dev() {
int fd_ = 0;
if(uartName.length() == 0){
cout << "devName is NULL." << endl;
return -1;
}
fd_ = open(uartName.c_str(), O_RDWR);
if(fd_ < 0){
cout << uartName << " is opened failed." << endl;
return -1;
}else{
cout << uartName << " is opened ok." << endl;
}
fd = fd_;
return fd_;
}
int close_serial()
{
close(fd);
}
void serial_init()
{
if(fd < 0){
cout << "serial_init failed ." << endl;
}
struct termios options;
tcgetattr(fd, &options);
options.c_cflag |= ( CLOCAL | CREAD );
options.c_cflag &= ~CSIZE;
options.c_cflag &= ~CRTSCTS;
options.c_cflag |= CS8;
options.c_cflag &= ~CSTOPB;
options.c_iflag |= IGNPAR;
options.c_iflag &= ~(ICRNL | IXON);
options.c_oflag = 0;
options.c_lflag = 0;
options.c_cflag |= CBAUDEX;
cfsetispeed(&options, speedBaud);
cfsetospeed(&options, speedBaud);
tcsetattr(fd,TCSANOW,&options);
cout << "serial_init ok." << endl;
}
int read_message(mavlink_message_t &message){
int result = 0;
uint8_t ch;
mavlink_status_t status;
uint8_t msgReceived = false;
result = read(fd, &ch, 1);
if(result > 0){
msgReceived = mavlink_parse_char(MAVLINK_COMM_0, ch, &message, &status);
if ( (lastStatus.packet_rx_drop_count != status.packet_rx_drop_count) )
{
printf("ERROR: DROPPED %d PACKETS\n", status.packet_rx_drop_count);
unsigned char v= ch;
fprintf(stderr,"%02x ", v);
}
lastStatus = status;
}
return msgReceived;
}
public:
string uartName;
speed_t speedBaud;
int fd;
mavlink_status_t lastStatus;
};
#endif