不是ComPort不毛病,看源码:
procedure TCustomComPort.ApplyTimeouts;
var
Timeouts: TCommTimeouts;
function GetTOValue(const Value: Integer): DWORD;
begin
if Value = -1 then
Result := MAXDWORD
else
Result := Value;
end;
begin
// if not connected or inside BeginUpdate/EndUpdate block, do nothing
if (FConnected) and (FUpdateCount = 0) and
(not ((csDesigning in ComponentState) or (csLoading in ComponentState))) then
begin
Timeouts.ReadIntervalTimeout := GetTOValue(FTimeouts.ReadInterval);
Timeouts.ReadTotalTimeoutMultiplier := GetTOValue(FTimeouts.ReadTotalMultiplier);
Timeouts.ReadTotalTimeoutConstant := GetTOValue(FTimeouts.ReadTotalConstant);
Timeouts.WriteTotalTimeoutMultiplier := GetTOValue(FTimeouts.WriteTotalMultiplier);
Timeouts.WriteTotalTimeoutConstant := GetTOValue(FTimeouts.WriteTotalConstant);
// apply settings
if not SetCommTimeouts(FHandle, Timeouts) then
raise EComPort.Create(CError_TimeoutsFailed, GetLastError);
end;
end;
Timeouts的ReadInterval实际上去设置硬件的ReadIntervalTimeout.
Spcomm有的是定时查询的方式读COM口;
而ComPort用Overlapped机制进行COM读写,只要COM有数据接收到,ComPort就能够从Event响应,并通知应用程序接收,所以,某种ComPort的实时性更好。
但是,Overlapped的Event被触发,并不是COM接入一段完整的信息才触发,是Windows自己决定的,我在多个计算机和不同的Windows版本上试过,其触发后接收到的字符数并不一样。因此,需要自己建一个缓冲区来处理数据。
看下面代码中的中文标注:
procedure TCustomComPort.CreateHandle;
begin
FHandle := CreateFile(
PChar('//./' + FPort),
GENERIC_READ or GENERIC_WRITE,
0,
nil,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED, // 以Overlapped方式打开COM口
0);
if FHandle = INVALID_HANDLE_VALUE then
raise EComPort.Create(CError_OpenFailed, GetLastError);
end;
procedure TComThread.Execute;
var
EventHandles: array[0..1] of THandle;
Overlapped: TOverlapped;
Signaled, BytesTrans, Mask: DWORD;
begin
FillChar(Overlapped, SizeOf(Overlapped), 0);
Overlapped.hEvent := CreateEvent(nil, True, True, nil);
EventHandles[0] := FStopEvent;
EventHandles[1] := Overlapped.hEvent; // COM口上的Overlapped事件
repeat
// 等待COM上的事件
// wait for event to occur on serial port
WaitCommEvent(FComPort.Handle, Mask, @Overlapped);
Signaled := WaitForMultipleObjects(2, @EventHandles, False, INFINITE);
// if event occurs, dispatch it
if (Signaled = WAIT_OBJECT_0 + 1)
and GetOverlappedResult(FComPort.Handle, Overlapped, BytesTrans, False)
then
begin
// 通知应用程序接收数据
FEvents := IntToEvents(Mask);
DispatchComMsg;
end;
until Signaled <> (WAIT_OBJECT_0 + 1);
// clear buffers
SetCommMask(FComPort.Handle, 0);
PurgeComm(FComPort.Handle, PURGE_TXCLEAR or PURGE_RXCLEAR);
CloseHandle(Overlapped.hEvent);
CloseHandle(FStopEvent);
end;