The overall use of Blog Park, although know the pattern, but draw on the other people's writing: Click on the Open link
Personal opinions and ideas:
1. Get enough data information first.
2. Judge the frame head, get the required data information
3. Frame end, execute next judgment
4. Removal of processed data
Done using the caching mechanism. First, by defining a member variable list<byte> buffer = new list<byte> (4096), which is used to hold all the data, in the receiving function, through the buffer. The AddRange () method continuously adds the received data to the buffer and checks the data in the buffer at the same time, if it reaches a certain length and the checksum result is correct (the calibration method is consistent with the sender and receiver), then processing. The specific code is as follows: code
Private list<byte> buffer = new list<byte> (4096);
private void Sp_datareceived (Objectsender, EventArgs e)//SP is a serial control
{
int n = sp. Bytestoread;
byte[] buf = new Byte[n];
Sp. Read (buf, 0, N);
1. Cache data
buffer. AddRange (BUF);
2. Integrity judgment while
(buffer). Count >= 4)//contains at least frame head (2 bytes), Length (1 bytes), checksum bit (1 bytes), varies according to design
{
//2.1 lookup header
if (buffer[0] = = 0x01)//Transmit data has frame headers, Used to determine
{
int len = buffer[2];
if (buffer). Count < Len + 4)//data area has not received full
{break
;
}
Get the complete data and copy it into the receivebytes to check the
buffer. CopyTo (0, receivebytes, 0, Len + 4);
byte valid; Start checksum
Valid = this. JY (receivebytes);
if (Jiaoyan!= receivebytes[len+3])//checksum fails, the last byte is a checksum bit
{
buffer. RemoveRange (0, Len + 4);
MessageBox.Show ("The packet is incorrect.) ");
Continue;
}
Buffer. RemoveRange (0, Len + 4);
Execute other code to process the data.
}
If else//frame header is not correct, remember to clear
{
buffer. RemoveAt (0);
}}}