串口协议匹配函数,避免串口数据接收时顺序换乱错误

按照协议匹配,避免串口数据接收时顺序换乱错误。

包头

长度

地址码

回复状态

校验和

包尾

备注

C0C0

02

F5

AA

YY

CF

成功

1,转移字符

                      a)              数据包基本格式中的数据长度、数据和校验和中如果出现关键字C0、

CF或CA则需要在其前端加上转义字符CA,即将数据C0、CF或CA发送成CAC0、CACF或CACA,将数据C0C0发送成CAC0CAC0。

                      b)              数据包基本格式中的数据长度length以有效数据的数量为准,即不

需要也不得将转义字符的数量累加上去。

                      c)              数据包校验和的计算从地址码开始累加到数据位的最后一位,只计

算有效数据,既不需要也不得将转义字符计算在内;

 1  public static Frame ReadFrame(SerialPort port)
 2         {
 3             byte[] data = new byte[4096];
 4             data[0] = 0xc0;
 5             data[1] = 0xc0;
 6             while (true)
 7             {
 8                 if (port.ReadByte() != 0xc0)
 9                     continue;
10                 if (port.ReadByte() != 0xc0)
11                     continue;
12                 int len = port.ReadByte();
13                 if (len < 2)
14                     continue;
15                 data[2] = (byte)len;
16                 int chk = 0, index = 3;
17                 bool escaping = false;
18                 for (int i = 0; i < len; i++)
19                 {
20                     int n = port.ReadByte();
21                     data[index++] = (byte)n;
22                     if (n == 0xca)
23                     {
24                         if (!escaping)
25                         {
26                             escaping = true;
27                             i--;
28                             continue;
29                         }
30                     }
31                     escaping = false;
32                     chk += n;
33                 }
34                 chk &= 0xff;
35                 if (port.ReadByte() != chk)
36                     continue;
37                 data[index++] = (byte)chk;
38                 if (port.ReadByte() != 0xcf)
39                     continue;
40                 data[index++] = 0xcf;
41                 byte[] rawData = new byte[index];
42                 System.Array.Copy(data, 0, rawData, 0, index);
43                 return new Frame(rawData);
44             }
45         }
原文地址:https://www.cnblogs.com/smartsensor/p/3929030.html