I'm trying to read data that I've written to the serial port /tty/USBS0. I've opened the port through serial_fd = open(serialport.str().c_str(), O_RDWR | O_NOCTTY | O_NDELAY);, and I am writing data through retVal2 = write(serial_fd, (void *)&msg, length);.
However, I am running into an issue where when I call read(), it stops there; in other words, it continues to read indefinitely.
void cmgGSP::read_thread(){
unsigned char msg[256];
unsigned char messagelength;
msg_header msgHeader; //msg_header is defined in cmgCOM.h
msgHeader.startByte = 0;
msgHeader.length = 0;
msgHeader.ID = 0;
int totalBytes;
int retVal;
cout<<"Scope Test -- In Read Thread"<<endl;
while(1) //infinte loop, since we're going to want to always be reading command data
{
cout<<"Scope Test -- In While(1)"<< endl;
totalBytes = 0;
while (totalBytes == 0) {
cout<<"Scope Test -- First While Loop"<<endl;
retVal = read(serial_fd, (unsigned char*)&msgHeader, 1);
cout<<"retVal: "<<retVal <<endl; //This does not get printed
if (retVal == -1)
{
printf("read() message failed: %s\n", strerror(errno));
}
if (msgHeader.startByte != FROM_CMG) {
printf("Bad start byte on read()\n");
totalBytes = 0;
} else {
cout<<"scope test 2"<<endl;
totalBytes+=retVal;
}
}
while (totalBytes < sizeof(msgHeader)) {
retVal = read(serial_fd, (unsigned char*)&msgHeader+totalBytes, sizeof(msgHeader)-totalBytes);
cout<< "in second while"<<endl;
if (retVal == -1){
printf("read() message failed: %s\n", strerror(errno));
}
totalBytes+=retVal;
}
if (msgHeader.startByte != START_BYTE) {
printf("Bad start byte on message\n");
continue;
}
else
{
printf("MSG RCV: StartByte=0x%X, Length=0x%X, ID=0x%X\n", msgHeader.startByte, msgHeader.ID, msgHeader.length);
break;
}
}
}
Above is the thread that I have created; however, the output never makes it past "Scope Test -- First While Loop". Even when I have explicitly called the thread after I write data, the result is the same: it reads infinitely. I know it's actually reading because if I disconnect the board while it's stuck, it starts printing "read() message failed ..."
Any help is appreciated - thanks!