您的位置:首页 > 其它

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

2014-08-22 11:37 260 查看
按照协议匹配,避免串口数据接收时顺序换乱错误。

包头

长度

地址码

回复状态

校验和

包尾

备注

C0C0

02

F5

AA

YY

CF

成功

1,转移字符

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

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

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

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

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

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

public static Frame ReadFrame(SerialPort port)
{
byte[] data = new byte[4096];
data[0] = 0xc0;
data[1] = 0xc0;
while (true)
{
if (port.ReadByte() != 0xc0)
continue;
if (port.ReadByte() != 0xc0)
continue;
int len = port.ReadByte();
if (len < 2)
continue;
data[2] = (byte)len;
int chk = 0, index = 3;
bool escaping = false;
for (int i = 0; i < len; i++)
{
int n = port.ReadByte();
data[index++] = (byte)n;
if (n == 0xca)
{
if (!escaping)
{
escaping = true;
i--;
continue;
}
}
escaping = false;
chk += n;
}
chk &= 0xff;
if (port.ReadByte() != chk)
continue;
data[index++] = (byte)chk;
if (port.ReadByte() != 0xcf)
continue;
data[index++] = 0xcf;
byte[] rawData = new byte[index];
System.Array.Copy(data, 0, rawData, 0, index);
return new Frame(rawData);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: