unit ReadComm;
interface
uses
Windows, Messages, SysUtils, Classes, Forms;
const
TimerSpeed = 200;
type
TOopsCommPort = class
protected
hMainWnd : THandle;
Dcb : Tdcb;
Commtimeouts : Tcommtimeouts;
ComPortHandle : THANDLE;
public
TempInBuffer : pointer;
function Open(hOwner: THandle;
CommName: Pchar) :Boolean;
procedure Close;
function TimerWndProc:Byte;
end;
var CommPort: TOopsCommPort;
implementation
function TOopsCommPort.Open(hOwner: THandle ;
CommName: Pchar): Boolean;
begin
hMainWnd := hOwner;
GetMem( TempInBuffer, 1024);
ComPortHandle := CreateFile(CommName,GENERIC_READ, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if ComPortHandle <= 0 then
begin
Result := False;
exit;
//Error Open Comm port;
end;
GetCommState(ComPortHandle, Dcb);
Dcb.BaudRate := 9600;// Baud rate to use
Dcb.Parity := 0;
// None parity to use
Dcb.StopBits := 0;
// 0 stop bits to use
Dcb.XONChar := #17;
// XON ASCII char - DC1, Ctrl-Q, ASCII 17
Dcb.XOFFChar := #19;
// XOFF ASCII char - DC3, Ctrl-S, ASCII 19
SetCommState(ComPortHandle, Dcb);
SetupComm( ComPortHandle, 512, 512);
GetCommTimeouts(ComPortHandle, Commtimeouts);
Commtimeouts.ReadIntervalTimeout := 1;
//maximum time in milliseconds
Commtimeouts.ReadTotalTimeoutMultiplier := 0;
Commtimeouts.ReadTotalTimeoutConstant := 1;
Commtimeouts.WriteTotalTimeoutMultiplier := 0;
Commtimeouts.WriteTotalTimeoutConstant := 0;
SetCommTimeouts(ComPortHandle, Commtimeouts);
SetTimer(hMainWnd, 1, TimerSpeed, nil );
Result := True;
end;
procedure TOopsCommPort.Close;
begin
KillTimer(hMainWnd, 1 );
CloseHandle(ComPortHandle);
ComPortHandle := 0;
FreeMem( TempInBuffer, 1024);
Destroy;
end;
function TOopsCommPort.TimerWndProc:Byte;
var nRead, nToRead, ComErrCode: UINT;
comStat: TComstat;
begin
Result:=$FF;
ClearCommError( ComPortHandle, ComErrCode, @comStat );
nRead := 0;
nToRead := ComStat.cbInQue;
if (nToRead > 0) and ReadFile(ComPortHandle, TempInBuffer^, nToRead, nRead, nil ) then
begin
if (nRead <> 0) then
Result:=(PByte(TempInBuffer))^;
end
end;
end.