I am sending a packet of sensor information over an Arduino XBee setup. The first byte of the packet is the packet header for synchronization. The second byte is the number of bytes in the packet (excluding header and packet size byte). The first byte of the packet payload is an identifying number for the sensor. The second payload byte is the data from the sensor. The third payload byte is an XOR for simple error checking. The first payload byte for the sensor ID will never need to be escaped, but the other two payload bytes may need to be escaped. The following is code I wrote for sending a single packet:
Serial.write(PACKET_HEADER); // Packet header for synchronization
Serial.write(calculatePacketSize(data, XOR)); // Size of packet
Serial.write(unitInfo);
// Check if the data byte needs to be escaped
if(data == ESCAPE || data == PACKET_HEADER) {
Serial.write(ESCAPE);
}
Serial.write(data);
// Check if the XOR byte needs to be escaped
if(XOR == ESCAPE || XOR == PACKET_HEADER) {
Serial.write(ESCAPE);
}
Serial.write(XOR);
What I am unsure about is how to process a packet on the receiving end. One issue I see is that because there are a variable number of payload bytes, I cannot check via Serial.available()
whether or not there are enough bytes to process the payload during this run through of loop()
. How do I go about processing a packet, and making sure the packet was received error free? I need to just discard incomplete packets or anything without a header.