title: Visual Studio 2012 C++ Keeping Serial COM port open in different classes
body: <p>I have my code in which in the first part (MyBehaviorModel();) I open a GUI window and as long as the window is open a loop is gonna update the position of an object by reading Serial COM port data after parsing the data and feeding it into the program. Currently the problem is that I open and close the handle using the following code on each loop which certainly is not the efficient and logical way and it causes delay in my program but that's the only way that it works.When I define the handle in the first class MyBehaviorModel(); and read the port in the second part (MyBehaviorModel::updatePosition(SReal dt)) it seems that the port is not known by (updatePosition(SReal dt)) and I don't get any data.</p>
  
  <pre><code>#include "MyBehaviorModel.h"
  #include &lt;sofa/core/ObjectFactory.h&gt;
  #include &lt;sofa/core/behavior/MechanicalState.h&gt;
  #include &lt;sofa/core/VecId.h&gt;
  #include &lt;sofa/defaulttype/VecTypes.h&gt;
  #include &lt;SofaUserInteraction/MechanicalStateController.h&gt;
  #include &lt;sofa/core/visual/VisualParams.h&gt;
  #include &lt;sofa/core/behavior/MechanicalState.h&gt;
  #include &lt;sofa/core/objectmodel/MouseEvent.h&gt;
  #include &lt;sofa/defaulttype/VecTypes.h&gt;
  #include &lt;sofa/defaulttype/RigidTypes.h&gt;
  #include &lt;sofa/defaulttype/Quat.h&gt;
  #include &lt;sofa/simulation/common/Node.h&gt;
  #include &lt;sofa/simulation/common/MechanicalVisitor.h&gt;
  #include &lt;sofa/simulation/common/UpdateMappingVisitor.h&gt;
  #include &lt;sofa/defaulttype/RigidTypes.h&gt;
  #include &lt;sofa/defaulttype/VecTypes.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;tchar.h&gt;
  #include &lt;string&gt;
  #include&lt;cstdlib&gt;
  #include&lt;iostream&gt;
  
  HANDLE m_hFile;
  bool error;
  char line[256];
  double xscale;
  double yscale;
  double prxscale;
  double pryscale;
  DWORD numberOfBytesRead = 0; //variable recieves number of bytes read reported by ReadFile
  // Current Values
  
  char * delim;
  char * result;
  char * result2;
  char * result3;
  char * pch;
  char * pch2;
  char * pch3;
  char * pch4;
  char * data;
  char * data2;
  double x;
  double y;
  
  HANDLE OpenComPort(int nPortNo=3,int BaudRate = CBR_9600,int ByteSize = 8,int Parity = NOPARITY,int StopBits
  = ONESTOPBIT);
  
  
  HANDLE OpenComPort(int nPortNo,int BaudRate,int ByteSize,int Parity,int StopBits)
  {
  LPCSTR strPort="COM3";
  BOOL fSuccess;
  COMMTIMEOUTS timeout;
  DCB dcb;
  
  //Create the handle for read the COM port
  m_hFile = CreateFileA( strPort, GENERIC_READ,
  (DWORD)NULL, // exclusive access
  NULL, // no security
  OPEN_EXISTING,
  FILE_ATTRIBUTE_NORMAL,
  NULL // hTemplate
  );
  if (INVALID_HANDLE_VALUE == m_hFile)
  {//Check whether the handle is valid or not.
  printf("Error: Could not open the RS232 port!");
  return NULL;
  }
  SetupComm(m_hFile,(DWORD)2048, (DWORD)2048);// setup the com parameters now that we have a handle
  // Set up the DCB with our settings
  fSuccess = GetCommState(m_hFile,&amp;dcb);// Get it first so we fill all members
  if (!fSuccess)
  {// Handle the error.
  printf("Error: Failed to Get the System Communication Settings.");
  return NULL;
  }
  dcb.BaudRate = BaudRate; // baud rate
  dcb.ByteSize = ByteSize; // data size
  dcb.Parity = Parity; // No Parity Bit
  dcb.StopBits = StopBits; // stop bits
  fSuccess = SetCommState(m_hFile, &amp;dcb); // assign it
  if ( fSuccess == 0 )
  {//Now check the configuration of the communication device is valid or not     after assign the com parameters
  printf("Error: In Control Setting for a Serial Communications Device.");
  return ("success!!!!");
  }
  // Set up the timeouts to use, they are quite short, since we will loop anyway.
  // Do not make them zero, else we will have a CPU load problem. Too large a value,
  // and we have to wait for comms to time out when shutting down.
  GetCommTimeouts(m_hFile, &amp;timeout); // fill timeout structure
  timeout.ReadIntervalTimeout = 0; // 500ms between incomming chars.
  timeout.ReadTotalTimeoutConstant = 0;
  timeout.ReadTotalTimeoutMultiplier = 0;
  timeout.WriteTotalTimeoutConstant = 0;
  timeout.WriteTotalTimeoutMultiplier = 0; // 60ms per char sent
  SetCommTimeouts(m_hFile, &amp;timeout);
  return m_hFile;
  }
  
  namespace sofa
  
  {
  
  namespace component
  {
  
  namespace behaviormodel
  {
  
  MyBehaviorModel::MyBehaviorModel():
  customUnsignedData(initData(&amp;customUnsignedData, (unsigned)1,"Custom     Unsigned Data","Example of unsigned data with custom widget")),
  regularUnsignedData(initData(&amp;regularUnsignedData, (unsigned)1,"Unsigned     Data","Example of unsigned data with standard widget"))
  {
  customUnsignedData.setWidget("widget_myData");
  
  
  
  }
  
  
  MyBehaviorModel::~MyBehaviorModel()
  {
  }
  
  void MyBehaviorModel::init()
  {
  
  }   
  
  void MyBehaviorModel::reinit()
  {
  
  }
  
  
  void MyBehaviorModel::updatePosition(SReal dt)
  { 
  m_hFile=OpenComPort(3,CBR_9600);
  
  if (m_hFile==NULL)
  {
  printf("COM3 port failed. Check hardware, and make sure no other program is accessing.");
  
  return;
  }
  else{
  printf("COM3 port is connected.");
  
  }
  
  if( m_hFile!=NULL)
  {
  
  error = ReadFile(m_hFile,LPVOID(line),255,&amp;numberOfBytesRead,NULL);
  line[numberOfBytesRead]=0;//terminate string here, so no random data is displayed.
  delim=strtok(line,"\n");
  if(delim!= NULL){
  size_t size=strlen(delim);
   result= (char*)memchr (delim,',' , size );
  }
  
   if(result!= NULL){
  result2= strtok (result,";"  );
   }
  
   if(result2!= NULL){
  pch=strchr(result2,',');
   }
  
  if(pch!= NULL){
  pch2=strtok(pch,",");
  }
  
  if(pch2!= NULL){
  result3= strtok (result,","  );
  x=atoi(pch2);
  xscale=(double)(x/100);
  if(  abs(xscale)&gt;0.3){
  prxscale=xscale;
   }
  }
  if(result== NULL){
  xscale=prxscale;
  }
  printf("%f\n",xscale);
  CloseHandle(m_hFile);
  
  }   
  //********************************************************************* 
  dy=0.00;
  using core::behavior::MechanicalState;
  mState1 = dynamic_cast&lt;MechanicalState&lt;sofa::defaulttype::Rigid3dTypes&gt; *&gt;        (this-&gt;getContext()-&gt;getMechanicalState());
  helper::WriteAccessor&lt;sofa::core::objectmodel::     Data&lt;sofa::defaulttype::Rigid3dTypes::VecCoord&gt; &gt; xp = *mState1-    &gt;write(core::VecCoordId::position());
  xp[0].getCenter()=sofa::defaulttype::Vec&lt;3,Real&gt;((Real)(xscale),(Real)dy,(Real)(0.00));
  
  
  }
  
  
  SOFA_DECL_CLASS(MyBehaviorModel)
  
  int MyBehaviorModelClass = core::RegisterObject("Dummy component with a     custom widget.").add&lt; MyBehaviorModel &gt;();
  
  
  } // namespace behaviormodel
  
  } // namespace component
  
  } // namespace sofa
  </code></pre>
  
  <p>I will be glad to have any feedback.Thanks in advance!</p>