I am trying to write and read data from a USB port in a central cygwin command. I managed to write and read the data when the device is connected, but I want to determine if there is another device or cannot send any data. My current test code is shown below (I tried a bunch of different things, but nothing worked).
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <stdio.h>
#include "USB_com.h"
#include "unistd.h"
void main()
{
int fd, value, bytes_read, bytes_written, nbytes, i, j;
char buffR[20];
char buffS[20];
fd = USB_init("/dev/com1");
printf("enter a message (write exit to terminate the session): ");
fgets(buffS, 19, stdin);
while (strncmp("exit", buffS, 4) != 0)
{
bytes_written = write(fd, buffS, 19);
sleep(1);
bytes_read = read(fd, buffR, 19);
printf("string recieved : %s\n", buffR);
memset(buffS, '\0', 19);
printf("enter a message (write exit to terminate the session): ");
fgets(buffS, 19, stdin);
}
USB_cleanup(fd);
}
And my USB_init.c for writing and reading from a USB device is shown below.
#include "USB_init.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
#ifndef BAUDRATE
#define BAUDRATE B9600
#endif
#define _POSIX_SOURCE 1
static int fd, c, res;
static struct termios oldtio, newtio;
static char *device;
int USB_init(char *modemdevice)
{
device = modemdevice;
fd = open (device, O_RDWR | O_NOCTTY );
if (fd < 0)
{
perror (device);
exit(-1);
}
tcgetattr (fd, &oldtio);
bzero (&newtio, sizeof (newtio));
newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR | ICRNL;
#if 0
newtio.c_oflag = ONLCR;
#else
newtio.c_oflag = 0;
#endif
#if 1
newtio.c_lflag = ICANON;
#else
newtio.c_lflag = 0;
#endif
newtio.c_cc[VINTR] = 0;
newtio.c_cc[VQUIT] = 0;
newtio.c_cc[VERASE] = 0;
newtio.c_cc[VKILL] = 0;
newtio.c_cc[VEOF] = 4;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 1;
newtio.c_cc[VSWTC] = 0;
newtio.c_cc[VSTART] = 0;
newtio.c_cc[VSTOP] = 0;
newtio.c_cc[VSUSP] = 0;
newtio.c_cc[VEOL] = 0;
newtio.c_cc[VREPRINT] = 0;
newtio.c_cc[VDISCARD] = 0;
newtio.c_cc[VWERASE] = 0;
newtio.c_cc[VLNEXT] = 0;
newtio.c_cc[VEOL2] = 0;
tcflush (fd, TCIFLUSH);
tcsetattr (fd, TCSANOW, &newtio);
return fd;
}
void USB_cleanup(int ifd){
if(ifd != fd) {
fprintf(stderr, "WARNING! file descriptor != the one returned by serial_init()\n");
}
tcsetattr (ifd, TCSANOW, &oldtio);
}
Can someone tell me how I can do something like read (fd, buffR, 19), but interrupt it after a while if I haven't received any data and printed something like printf ("no contact with device ")?
I am very grateful for any suggestions on how to solve this!