#include #include #include #include #include #include #include "rs232.h" typedef unsigned char byte; Comm::CommStatus Comm::open() { fd = ::open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY); if (-1 == fd) return COMM_ERR; struct termios options; tcgetattr(fd, &options); tcflush(fd, TCIFLUSH); options.c_cflag = CBAUD | B9600 | CS8 | CREAD | CLOCAL; options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); options.c_iflag &= ~(INPCK | ISTRIP); options.c_iflag &= ~(IXON | IXOFF | IXANY); options.c_oflag &= ~OPOST; cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); tcsetattr(fd, TCSANOW, &options); return COMM_OK; } Comm::CommStatus Comm::send(const byte *const data, const unsigned len) { int status = ::write(fd, data, len); if (status < 0) return COMM_ERR; else return COMM_OK; } Comm::CommStatus Comm::recvbyte(byte *const data) { int status = ::read(fd, data, 1); if (status < 0 && errno == EAGAIN) return COMM_NULL; else if(status < 0) return COMM_ERR; return COMM_OK; } Comm::CommStatus Comm::recv(byte* data, int size) { CommStatus st = recvbyte(data); if (st != COMM_OK) return st; if (1 == size--) return st; fcntl(fd, F_SETFL, 0); while (size-- > 0) { st = recvbyte(++data); if (st != COMM_OK) break; } fcntl(fd, F_SETFL, FNDELAY); return st; }