How to wait for serial port input in the middle of a program

advertisements

I am writing a program to control an Iridium modem that communicates with a satellite. After each AT command is sent, the modem sends a reply back (depending on the command) to indicate the command was successful.

Right now I have it implemented so that the program just waits 10 seconds between the transmission of each command to the modem, but this is a bit risky because it does not allow for error handling in case the command is not successfully interpreted. The only way I know how to read serial input is with while(fgets( , ,)), so I am wondering how I would be able to have the program wait for a reply from the modem over the serial port and check what it is before the next command is sent instead of having a uniform delay.

I'm using a linux OS.

FILE *out = fopen(portName.c_str(), "w");//sets the serial port

for(int i =0; i<(sizeof(messageArray)/sizeof(messageArray[0])); i++)
{
  //creates a string with the AT command that writes to the module
  std::string line1("AT+SBDWT=");
  line1+=convertInt( messageArray[i].numChar);
  line1+=" ";
  line1+=convertInt(messageArray[i].packetNumber);
  line1+=" ";
  line1+=messageArray[i].data;
  line1+=std::string("\r\n");

  //creates a string with the AT command that initiates the SBD session
  std::string line2("AT+SBDI");
  line2+=std::string("\r\n");

  fputs(line1.c_str(), out); //sends to serial port
  usleep(10000000);     //Pauses  between the addition of each packet.

  fputs(line2.c_str(), out); //sends to serial port

  usleep(10000000);
}


Use select or poll on the file descriptor corresponding to the serial port, which will return when the descriptor is ready for reading.

Something like this:

int fd = fileno(stdin);  /* If the serial port is on stdin */
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd, &fds);
struct timeval timeout = { 10, 0 }; /* 10 seconds */
int ret = select(fd+1, &fds, NULL, NULL, &timeout);
/* ret == 0 means timeout, ret == 1 means descriptor is ready for reading,
   ret == -1 means error (check errno) */