Best practice to check com port exists and is acti

Hi all,

 
Whats the best way to test if a USB port exists and is active before I start sending data to it. I'd like to trap this kind of error and advise the user to go and rescan/reset the port before continuing. Our application talks to an FTDI  chip for legacy USB communications.
 
In this way I can make a gracefull exit by closing the port etc otherwise the application is prone to locking up.
 
Also how do I use the GetComPortNames procedure?
 
Thanks - all help and suggestions appreciated
 
Roger B
 
 

To detect if a COM port is available you could

1) try to open it and catch the exception when this fails. The exception indicates the COM port is not availble
2) use GetCOMPortNames like for example:

var
 sl: TStringList;
begin
  sl := TStringList.Create;
  vacomm1.GetComPortNames(sl);
  ListBox1.Items.Assign(sl);
  sl.Free;
end;

Closing a COM port is always done via vaComm.Close;

And how i can detect if was disconnected when app is running?

Also you can post a example managing this kind of exception for async32?

The OnError event should be triggered. The error codes that can be returned can be one of the following:

https://msdn.microsoft.com/en-us/library/windows/desktop/aa363180(v=vs.85).aspx

Bruno Fierens2017-12-26 10:49:13

I get a barrage of dialog boxes complaining if a VaComm1->WriteText(asSomeString); is sent after the serial (USB) is pulled during a serial session.


I have tried to trap the error message unsuccessfully with try / catch block on the VaComm1->WriteText line ....   However, I found a work around that works:

try
{
VaComm1->ReadBufUsed();     //... Did we LOSE the COM port (disconnected from Windows)
VaComm1->WriteText(asMsg);
}
catch (...)
{
Memo1->Lines->Add("Failed sending message to COM port");
VaComm1->Close();
}

This solution, provided a means from having my clients bring up Windows Task Manager and killing my application.   Not sure why I couldn't "catch" the actual offending line, VaComm1->WriteText().

Hope this is helpful for others.

Thanks for sharing.

When working with USB devices, note that the only way Windows notifies applications of USB device removal is: https://docs.microsoft.com/en-us/windows/desktop/devio/wm-devicechange  , at serial port API level, Windows does not signal this unfortunately.
1 Like

So the only way to detect if a USB cable disconnect cause the virtual COM port "vanish"
is to trap this WM_DEVICECHANGE message ?

Regards,
Marco

That is correct.