以下是通讯部分,我不停的调用来进行不同strIPCMachineID数据的收集!
通讯的过程是先叫地址,回应地址,再发命令,回应数据。
通讯不上的时候,并没有显示我设定的错误提示,而是异常退出的fail-3,我估计是在打开串口的时候出错的!
function TFrmMain.Communication(strIPCMachineID:string):Boolean;
var
strCmd:String;
intTemp,j,intSum,intMachineId,intCom:integer;
begin
try
//com1.Close;
intCom:=strToint(copy(strIPCMachineID,1,2)) ;
Com1.DeviceName:='Com'+intTostr(intCom);
intMachineID:=strToint(copy(strIPCMachineID,3,2));
Com1.BaudRate:=TBaudRate(6);
Com1.Parity:=paMark; //发地址祯
intGetDataSum:=0;
intStep:=1;
com1.Open;
for j:=0 to 20 do
intBuffer[j]:=0;
fIsRecieve:=false;
fIsWaiting:=True;
if (not SendData(chr(intMachineID))) then
begin
Com1.Close;
btnclose.Caption:='not sendData';
btnClose.Refresh;
result:=false;
exit;
end;
intTemp:=GetTickCount;
while fIsWaiting do //等待----〉结束命令在Comm1RxChar
begin
if ((GetTickCount-intTemp)>1000) and (not fIsRecieve) then
begin
com1.Close;
btnclose.Caption:='fail-1';
btnClose.Refresh;
result:=false;
exit;
end;
if (GetTickCount-intTemp)>5000 then
begin
com1.Close;
btnclose.Caption:='Error-1';
btnClose.Refresh;
result:=false;
exit;
end;
Application.ProcessMessages;
end;
if intBuffer[0]<>intMachineID then
begin
com1.Close;
btnclose.Caption:='Num-1';
btnClose.Refresh;
result:=false;
exit;
end;
//准备发送的命令字
strCmd:=chr(intMachineID);
strCmd:=strCmd+chr(0)+chr(0)+chr(0)+chr(0);
strCmd:=strCmd+chr(0)+chr(0)+chr(0);
intGetDataSum:=0;
Com1.Parity:=paSpace;
intStep:=2;
for j:=0 to 20 do
intBuffer[j]:=0;
fIsRecieve:=false;
fIsWaiting:=True;
if (not SendData(strCmd)) then
begin
Com1.Close;
btnclose.Caption:='not2';
btnClose.Refresh;
result:=false;
exit;
end;
intTemp:=GetTickCount;
while fIsWaiting do //等待----〉结束命令在Comm1RxChar
begin
if ((GetTickCount-intTemp)>2000) and (not fIsRecieve) then
begin
com1.Close;
btnclose.Caption:='fail';
btnClose.Refresh;
result:=false;
exit;
end;
if (GetTickCount-intTemp)>10000 then
begin
com1.Close;
btnclose.Caption:='Error';
btnClose.Refresh;
result:=false;
exit;
end;
Application.ProcessMessages;
end;
com1.Close;
if intBuffer[0]<>intMachineID then //若回应的机台编号不符则跳出
begin
//com1.Close;
btnclose.Caption:='Num-2';
btnClose.Refresh;
result:=false;
exit;
end;
if intBuffer[19]<>0 then //若回应的命令字不符则跳出
begin
//com1.Close;
btnclose.Caption:='Num-3';
btnClose.Refresh;
result:=false;
exit;
end;
//判断校验和
intSum:=0;
for intTemp:=0 to 19 do //计算校验和
intSum:=intSum+intBuffer[intTemp];
intSum:=intSum mod 256;
if intSum<>intBuffer[20] then //判断校验和
begin
//com1.Close;
btnclose.Caption:='Num-4';
btnClose.Refresh;
result:=false;
exit;
end;
btnclose.Caption:='ok-1';
btnClose.Refresh;
if ProcessData(strIPCMachineId) then
begin
//com1.Close;
btnclose.Caption:='ok';
btnClose.Refresh;
result:=true;
exit;
end
else
begin
btnclose.Caption:='fail-2';
btnClose.Refresh;
result:=false;
exit;
end;
except
result:=false;
btnclose.Caption:='fail-3';
btnClose.Refresh;
//com1.Close;
end;
end;