34 #include <sys/ioctl.h>
36 #include <sys/types.h>
40 #include <boost/format.hpp>
42 static inline tcflag_t
43 __bitrate_to_flag(
unsigned int bitrate)
84 this->device = device;
85 this->bitrate = bitrate;
97 tcflag_t bitrate = __bitrate_to_flag(this->bitrate);
101 fprintf(stderr,
"Invalid bitrate '%d' for serial device\n", this->bitrate);
107 fd =
::open(device, O_RDWR | O_NOCTTY);
111 fprintf(stderr,
"Failed to open serial device '%s' (errno: %s)\n", device, strerror(errno));
115 if (::ioctl(fd, TIOCEXCL))
117 fprintf(stderr,
"Failed to lock serial device '%s' (errno: %s)\n", device, strerror(errno));
126 stderr,
"Device '%s' is not a terminal device (errno: %s)!\n", device, strerror(errno));
131 struct termios settings;
134 settings.c_iflag = IGNBRK
140 settings.c_oflag = 0;
143 settings.c_cflag = bitrate | CS8
149 settings.c_lflag = 0;
153 settings.c_cc[VTIME] = 10;
156 settings.c_cc[VMIN] = 0;
159 tcflush(fd, TCIFLUSH);
161 tcsetattr(fd, TCSANOW, &settings);
184 res = blockingReadAll(buf, len);
188 std::cerr <<
"Failed to read from serial device" << std::endl;
195 SerialInterface::blockingReadAll(
unsigned char* buf,
unsigned int len)
197 int dataToRead = len;
201 int res =
::read(fd, buf, dataToRead);
218 throw new std::runtime_error(
"Internal error: dataToRead < 0");
228 return (::
write(fd, (
void*)buf, len));
234 return str(boost::format(
"SerialInterface(connected=%1%, device=%2%, bitrate=%3%, fd=%4%)") %