34 #include <sys/types.h>
36 #include <sys/ioctl.h>
38 #include <boost/format.hpp>
40 static inline tcflag_t __bitrate_to_flag(
unsigned int bitrate)
82 this->device = device;
83 this->bitrate = bitrate;
95 tcflag_t bitrate = __bitrate_to_flag(this->bitrate);
99 fprintf(stderr,
"Invalid bitrate '%d' for serial device\n", this->bitrate);
105 fd =
::open(device, O_RDWR | O_NOCTTY);
109 fprintf(stderr,
"Failed to open serial device '%s' (errno: %s)\n", device, strerror(errno));
113 if (::ioctl(fd, TIOCEXCL))
115 fprintf(stderr,
"Failed to lock serial device '%s' (errno: %s)\n", device, strerror(errno));
124 fprintf(stderr,
"Device '%s' is not a terminal device (errno: %s)!\n", device, strerror(errno));
129 struct termios settings;
132 settings.c_iflag = IGNBRK
138 settings.c_oflag = 0;
141 settings.c_cflag = bitrate
148 settings.c_lflag = 0;
152 settings.c_cc[VTIME] = 10;
155 settings.c_cc[VMIN] = 0;
158 tcflush(fd, TCIFLUSH);
160 tcsetattr(fd, TCSANOW, &settings);
181 res = blockingReadAll(buf, len);
185 std::cerr <<
"Failed to read from serial device" << std::endl;
192 int SerialInterface::blockingReadAll(
unsigned char* buf,
unsigned int len)
194 int dataToRead = len;
198 int res =
::read(fd, buf, dataToRead);
215 throw new std::runtime_error(
"Internal error: dataToRead < 0");
224 return (::
write(fd, (
void*) buf, len));
230 return str(boost::format(
"SerialInterface(connected=%1%, device=%2%, bitrate=%3%, fd=%4%)")