unit brcom;

interface

uses Windows, Messages, SysUtils;

function abreCom (com: string): boolean;
procedure escreveCom (s: string);
function leCom: string;
procedure fechaCom;

implementation

var
    comId: THandle;

{ constantes, tipos e variaveis }

function abreCom (com: string): boolean;
var
    modemDCB: TDCB;              { controles da comunicacao }

begin
    abreCom := false;

    comId := CreateFile (pchar(com), GENERIC_READ OR GENERIC_WRITE, 0, NIL,
          OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
    if comId = INVALID_HANDLE_VALUE then exit;

    GetCommState(comID, modemDCB);
    modemDCB.BaudRate := 300;
    modemDCB.ByteSize := 8;
    modemDCB.Parity := NOPARITY;
    modemDCB.StopBits := ONESTOPBIT;
    setCommState (comId, modemDCB);

    abreCom := true;
end;

procedure escreveCom (s: string);
var nescritos: DWORD;
    p: array [0..144] of char;
begin
    strpCopy (p, s);
    WriteFile (comId, p, length(s), nescritos, NIL);
end;

function leCom: string;
var nescritos: DWORD;
    p: array [0..0] of char;
    s: string;
begin
    sleep (500);
    repeat
        ReadFile (comId, p, 1, nescritos, NIL);
        s := s + p[0];
    until p[0] = #$0a;
    lecom := s;
end;

procedure fechaCom;
begin
    closeHandle (comID);
end;

end.
