speed_t portSpeed(int port_speed)
{
if(port_speed == 19200) return B19200;
return B9600;
}
int main(int argc, char *argv[]) {
int baudrate = 9600;
string device = «/dev/ttymxc1»;
fd_set read_fs;
fd_set write_fs;
fd_set error_fs;
int fd = -1;
static const int buf_size = 39;
unsigned char buf[buf_size] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
struct termios options;
try
{
fd = open(device.data(), O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK );
if (fd == -1)
{
printf("ComPort -> Could not open device %s !!!", device.data());
return 0;
}
else
{
printf("ComPort %s is open !!!\n", device.data());
fcntl(fd, F_SETFL, 0);
}
tcgetattr(fd, &options);
options.c_cflag = CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_iflag |= IGNBRK;
options.c_iflag &= ~BRKINT;
options.c_iflag &= ~ICRNL;
options.c_oflag = 0;
options.c_lflag = 0;
options.c_line = 0;
options.c_cc[VTIME] = 0;
options.c_cc[VMIN] = 0;
if(cfsetispeed(&options, portSpeed(baudrate))<0 ||
cfsetospeed(&options, portSpeed(baudrate)<0))
{
printf("Unable to set com-port baudrate!!!\n");
close(fd);
return 0;
}
tcflush(fd, TCIOFLUSH);
tcsetattr(fd, TCSANOW, &options);
}
catch(...)
{
printf("Device open Exception!\n");
printf("Exit from thread!\n");
return 0;
}
struct timeval timeout_wait = { 0, 1000 };
struct timespec sp = { 1, 0 }; //1 секунда
int ret = 0;
static int frame_write_size = 7;
unsigned char frame_write[frame_write_size] = {0x53, 0x03, 0x0F, 0x77, 0x00, 0x2C, 0x0D}; //тестовая посылка
while(1)
{
try
{
if(kbhit()!=0) break;
FD_ZERO (&read_fs);
FD_ZERO (&write_fs);
FD_ZERO (&error_fs);
FD_SET(fd, &read_fs);
FD_SET(fd, &write_fs);
FD_SET(fd, &error_fs);
if ((ret = select(fd+1, &read_fs, &write_fs, &error_fs, &timeout_wait)) < 0)
{
continue;
}
if (FD_ISSET(fd, &error_fs))
{
printf("ComPort: ERROR DESCRIPTOR SELECTED!!! \n");
nanosleep(&sp, NULL);
continue;
}
if (FD_ISSET(fd, &read_fs) )
{
//memset(buf,0x00, sizeof(unsigned char)*buf_size);
//buf[buf_size] = {0};
buf[0] = 0;
int bytes_read = read(fd, buf, buf_size);
if(bytes_read>0)
{
printf("Bytes accepted: ");
printf_asHex(buf, bytes_read);
usleep(3000);//пауза на линии
}
else
{
printf("Socket read ERROR!!!\n");
nanosleep(&sp, NULL);
}
continue;
}
if (FD_ISSET(fd, &write_fs))
{
int bytes_write = write(fd, frame_write, frame_write_size);
tcdrain( fd );
if(bytes_write != frame_write_size)
{
printf("Data write ERROR: bytes_write(%d) != frame_write_size(%d)\n",bytes_write,frame_write_size);
nanosleep(&sp, NULL);
}
else
{
usleep(15000);//15 миллисекунд - искусственно подобранная задержка, чтобы всё пролезало
}
}
continue;
}
}
catch(...)
{
printf("ComPort read/write Exception!\n");
break;
}
}
if(fd!=-1)
{
try
{
close(fd);
}
catch(...)
{
}
}
printf("EXIT MAIN\n!!!");
return 0;
}