I know this question has already been asked many times and I have studied and also found in what part of my code is giving this error. I am asking this to get the alternative for that solution. I am dealing with a situation where I am reciving a large packet serially. I have connected a signal to read the serial data like below:
connect(&Serial, SIGNAL(readyRead()), this, SLOT(SerialRead()));
So SerialRead()
is called everytime when the new serial data is available to read. I am trying to read a packet whoose length is not fixed. Now whats happening is SerialRead()
reads few bytes of the data and then again goes for reading. As the packet length is big, it cannot read the complete packet in one run & I cannot move further in my code till I have full packet. Luckily, I studied the packet and found out that the 4th byte of the packet signifies the length of the packet. So now I have the length, that means I can just check if I have received the complete bytes as per the 4th byte and then move further. To do this, I made the following code:
QString serialData,numberOfBytes;
QStringList serialPacket;
void MainWindow::SerialRead()
{
serialData.append(Serial.readAll()); //reading all the serial data
serialPacket = serialData.split(" ");
numberOfBytes = Convert.ToDec(serialPacket[3]); //getting the length of the packer
if(serialPacket.count() >= (numberOfBytes.toInt())) //checking if all the bytes (full packet) is received or not
{
DisplayMessage(serialPacket);
}
}
So when I receive the full packet, I go to my DisplayMessage function to process the packet. Now when the ASSERT Failure
error came, I commented out the line numberOfBytes = Convert.ToDec(serialPacket[3]);
and its remaining code and then there was no error. So I think the error tries to say that what if serialPacket[3] contains no data then it is giving error. If this is true then what is the replacement of it.? Can anyone tell me a good way to check if full packet is received or not.? Thanks
EDIT:
void MainWindow::SerialRead()
{
serialData.append(Serial.readAll()); //Reading the data
if(!serialData.isEmpty()) //Checking if data is empty or not
{
serialPacket = serialData.split(" ",QString::SkipEmptyParts);
if(serialPacket.contains("CC")) //Checking if it contains "CC"
{
int index = serialPacket.indexOf("CC");
numberOfBytes = Convert.ToDec(serialPacket[index+2]);
if(serialPacket.count() >= ((numberOfBytes.toInt())+2))
{
DisplayMessage(serialPacket);
}
}
}
}