帧校验和奇偶校验的问题
这个函数看不大懂,求高手解释function checkData(buffer : array of byte; bufferlength : integer ;var ainfo : CommunicationInfo) : integer;
var
i : integer;
startbyytepos : integer;
FindStartByte : boolean;
templen : integer;
index68:integer;
checksum:byte;
checkerror:boolean;
tempint:integer;
begin
startbyytepos := -1;
if ainfo.waitforcomplete then //如果是上一桢的后续部分,则合并到上一桢。
begin
ainfo.waitforcomplete:=false;
if ( bufferlength+ainfo.RxBufLengthAll )>300 then
begin
bufferlength := 300 - ainfo.RxBufLengthAll;
end;
for i:=0 to bufferlength -1 do
begin
ainfo.ReceiveBuffer[ ainfo.RxBufLengthAll + i ] := buffer[i];
end;
ainfo.RxBufLengthAll := ainfo.RxBufLengthAll + bufferlength;
//检查是否是一桢已满(如:将一桢分成3片和4片的情况)
for i:=0 to ainfo.RxBufLengthAll -1 do
if (ainfo.ReceiveBuffer[i]=$68) and (ainfo.ReceiveBuffer[i+3]=$68) then
begin
startbyytepos := i ;
break;
end;
if ( startbyytepos <> -1 ) and ( ainfo.RxBufLengthAll < ainfo.ReceiveBuffer[startbyytepos + 1 ]) then
begin
ainfo.waitforcomplete:=true;
end;
end
//如果是新的一桢。
else
begin
for i:=0 to bufferlength-1 do
if (buffer[i]=$68) and (buffer[i+3]=$68) then
begin
startbyytepos:=i;
break;
end;
if startbyytepos <> -1 then //有68 ** ** 68
begin
i:= buffer[startbyytepos+1];
templen:=buffer[startbyytepos+1];
if bufferlength < (startbyytepos + 4 + i + 2 ) then //收到的数据<应该有的长度,等待继续接收。
begin
ainfo.waitforcomplete:=true;
for i:=0 to bufferlength - 1 do ainfo.ReceiveBuffer[i]:=buffer[i];
ainfo.RxBufLengthAll := bufferlength;
end
else
begin
for i:=0 to templen + 8 do
begin
ainfo.ReceiveBuffer[i]:= buffer[startbyytepos + i ]; //多读了几个字节
end;
ainfo.RxBufLengthAll := bufferlength;
end;
end
else
begin
exit;
end;
end;
if ainfo.waitforcomplete then exit;
{开始分析命令,先三步校验,若校验错,设置校验失败标志,校验成功后再分析。}
index68:=-1;
checkerror := false;
For i := 0 To ainfo.RxBufLengthAll-1 do
If (ainfo.ReceiveBuffer[i]=$68) and (ainfo.ReceiveBuffer[i+3]=$68) Then
begin
index68 := i;
break;
end;
If index68=-1 then checkerror := true;//无68..68。
For i := 0 To ainfo.RxBufLengthAll - index68 -1 do
ainfo.DataBuffer[i]:= ainfo.ReceiveBuffer[index68+i];
ainfo.DataBufLength:=ainfo.RxBufLengthAll-index68;
checksum:=0;
For i:=1 to ainfo.DataBuffer[2] do
checksum := checksum + ainfo.DataBuffer[i+3];
If (checksum <> ainfo.DataBuffer[ainfo.DataBuffer[2]+4]) or
(ainfo.DataBuffer[ainfo.DataBuffer[2]+5]<>$16) then checkerror:=true;
if checkerror then //校验错误。
begin
Exit;
end;
result := 1 ;
end;