How to wait for COM port receive event before sending more data in a loop

后端 未结 2 1217
北海茫月
北海茫月 2021-01-16 07:23

I\'m working on a small component for writing and reading AT Commands using an old Sony Ericsson phone. Sending and writing to/from the phone is no problem at all, however I

2条回答
  •  不思量自难忘°
    2021-01-16 07:44

    While AsyncPro does have some solutions for this (ontriggerdata), they are event based and make code difficult to read/understand.

    here is SendAndWaitForResponse with AsyncPro (like Remy suggested):

    TForm1 = class(TForm)
     ...
    private
        IOEvent           : THandle; // used for IO events
        IORx              : string;
        Comport           : TapdComport;
    ...
    
    
    procedure TForm1.ComportTriggerAvail(CP: TObject; Count: Word);
    
    var i       : integer;
    
    begin
     for i:=1 to Count do
      IORx:=IORx+Comport.GetChar;
     SetEvent(IOEvent);
    end;
    
    function TForm1.SerialSAWR(tx : string; TimeOut : integer) : boolean;
    begin
     Result := False;
     try
      IORx := ''; // your global var
      ResetEvent(IOEvent);
      Comport.PutString(tx);
      Result := WaitForSingleObject(IOEvent, TimeOut) = WAIT_OBJECT_0;
     except
      on E : Exception do
       // dosomething with exception
     end;
    end;
    
    // constructor part
    IOEvent := CreateEvent(nil, True, False, nil);
    // destructor part
     if IOEvent <> 0 then
      CloseHandle(IOEvent);
    

    Best solution is to create a thread with the comport so your GUI won't be blocked. I have several applications in production with Asyncpro this way and it works like a charm...

提交回复
热议问题