How does OpenTAP know a instrument (resource) connection failed

Hi!

I can succesfully open a connection to an instrument using a COMport.
But I want to know how can I let OpenTAP/Pathwave know when the initial connection of a resource did not complete succesfully.

This is my code that is executed when the connection fails

Log.Error( "Could not communicate to " + mComPort );
mC_ComClient.Close();
base.Close();
//this.Close(); // this closes the COM connection but OpenTAP still returns the same log
IsConnected = false; // this does nothing, opentap still says it is opened

And these are the logs after I open the connection

08:29:21.408  COM instrument COM connection opened
08:29:21.408  COM instrument Testing Connection...
08:29:21.459  COM instrument Could not communicate to COM1
08:29:21.472  COM instrument Resource "COM instrument" opened. [119 ms]
08:29:34.222  COM instrument Resource "COM instrument" closed. [26.7 us]

Line 3 of the logs is coming from the Log.Error.

What should I change to let OpenTAP/Pathwave know there was an error connecting to the instrument?

1 Like

@lucappelman Welcome to the Forum!

The best way to handle these is to throw an Exception. You can catch the Exception in your Close method as well as do any cleanup and Logging. This ensures that when the Exception occurs your Close method will always be called, and you don’t leave any partially instantiated objects around.

1 Like

Sorry for the late reply.

How would I catch a Exception in the Close function if it’s thrown in the Open function.
I am new to C# so maybe it has some magic I do not know about, or simply misunderstood you.
For as far as I know you need a try {} catch (Exception) {} in the same function.

Can you provide an example?

1 Like

@lucappelman you are right. It would be easiest just to handle the exceptions within the Open method. Sorry for the confusion.

So you can have:

if(ConnectionFails)
{
    Log.Error( "Could not communicate to " + mComPort );
    throw new TimeoutException();
}
IsConnected = true;

public void Close()
{
    if(IsConnected)
    {
        //Standard close logic
         mC_ComClient.Close();
         base.Close();
    }
   else
   {
        //Failure logic
        mC_ComClient.Close();
         base.Close();
   }
  IsConnected = false;
}

The call to initialize devices has a Try/Catch so your thrown exception will get caught there and trigger the call to the Close() method.