示例#1
0
int RCX_open(int type, char *portname){
  //Opens the connections to the RCX via tower on serial or usb port.
  //type 1: serial port, type 2: USB port
  //portname for serial port is "COM1" for example
  //portname for USB port is "\\\\.\\LEGOTOWER1" for example
  //returns 0 if failed, 1 if successful

  if (type==1){//open serial port
    RCX_port = CreateFileA("COM6", GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_NEW, FILE_FLAG_WRITE_THROUGH, 0);

    if (RCX_port == INVALID_HANDLE_VALUE) return(0);

    //set data protocol format
    GetCommState(RCX_port,&dcb);
    FillMemory(&dcb, sizeof(dcb), 0);
    dcb.DCBlength = sizeof(dcb);
    dcb.BaudRate=CBR_2400;
    dcb.fBinary=1;
    dcb.fParity=1;
    dcb.fDtrControl=DTR_CONTROL_ENABLE;
    dcb.fRtsControl=RTS_CONTROL_ENABLE;
    dcb.ByteSize=8;
    dcb.Parity=ODDPARITY;
    dcb.StopBits=ONESTOPBIT;
    if (!SetCommState(RCX_port, &dcb)){
      RCX_close();
      return(0);
    }


    GetCommTimeouts(RCX_port,&tout);
    tout.ReadIntervalTimeout=250;
    tout.ReadTotalTimeoutConstant=10;
    tout.ReadTotalTimeoutMultiplier=10;
    tout.WriteTotalTimeoutConstant=10;
    tout.WriteTotalTimeoutMultiplier=10;
    SetCommTimeouts(RCX_port,&tout);

    SetupComm(RCX_port,65536,65536);
  } else { //type 2: open USB port
    RCX_port = CreateFileA(portname, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH | FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, 0);
    if (RCX_port == INVALID_HANDLE_VALUE) return(0);

    GetCommTimeouts(RCX_port,&tout);
    tout.ReadIntervalTimeout=250;
    tout.ReadTotalTimeoutConstant=10;
    tout.ReadTotalTimeoutMultiplier=10;
    tout.WriteTotalTimeoutConstant=10;
    tout.WriteTotalTimeoutMultiplier=10;
    SetCommTimeouts(RCX_port,&tout);
  }


  return(1);
}
int SerialPortImpl::pollImpl(char* buffer, std::size_t size, const Poco::Timespan& timeout)
{
	COMMTIMEOUTS prevCTO;
	if (!GetCommTimeouts(_handle, &prevCTO))
	{
		throw Poco::IOException("error getting serial port timeouts");
	}

	COMMTIMEOUTS cto;
	cto.ReadIntervalTimeout         = CHARACTER_TIMEOUT;
	cto.ReadTotalTimeoutConstant    = static_cast<DWORD>(timeout.totalMilliseconds());
	cto.ReadTotalTimeoutMultiplier  = 0;
	cto.WriteTotalTimeoutConstant   = MAXDWORD;
	cto.WriteTotalTimeoutMultiplier = 0;
	if (!SetCommTimeouts(_handle, &cto))
	{
		throw Poco::IOException("error setting serial port timeouts on serial port");
	}

	try
	{
		DWORD bytesRead = 0;
		if (!ReadFile(_handle, buffer, size, &bytesRead, NULL))
		{
			throw Poco::IOException("failed to read from serial port");
		}
		SetCommTimeouts(_handle, &prevCTO);
		return (bytesRead == 0) ? -1 : bytesRead;
	}
	catch (...)
	{
		SetCommTimeouts(_handle, &prevCTO);
		throw;
	}
}
示例#3
0
/**
 * @brief This function initializes the serial port for both directions (reading/writing) with fixed parameters:
 * \n baud=38400, parity=N, data=8, stop=1
 * @param *serialPort is a pointer to the name of the serial port
 * @return TRUE if success, FALSE in case of error.
 */
BOOL initSerial(CHAR *serialPort)
{
	COMMTIMEOUTS timeouts;
	int rc;
	DCB dcbStruct;
	CHAR msgTextBuf[256];

	// open the comm port.
	comPort = CreateFile(serialPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, NULL);
	if (comPort == INVALID_HANDLE_VALUE)
	{
		printf("Unable to open %s. \n", serialPort);
		return FALSE;
	}

	// get the current DCB, and adjust a few bits to our liking.
	memset(&dcbStruct, 0, sizeof(dcbStruct));

	dcbStruct.DCBlength = sizeof(dcbStruct);
	// printf("dcbStruct.DCBlength(): %ld \n", dcbStruct.DCBlength);

	rc = GetCommState(comPort, &dcbStruct);
	if (rc == 0)
	{
		printf("\nGetCommState(): ");
		printf(getLastErrorText(msgTextBuf, sizeof(msgTextBuf)));
		return FALSE;
	}

	// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363143(v=vs.85).aspx
	BuildCommDCB("baud=38400 parity=N data=8 stop=1", &dcbStruct);

	rc = SetCommState(comPort, &dcbStruct);
	// If the function fails, the return value is zero.
	if (rc == 0)
	{
		printf("\nSetCommState(): ");
		printf(getLastErrorText(msgTextBuf, sizeof(msgTextBuf)));
		return FALSE;
	}

	// Retrieve the timeout parameters for all read and write operations on the port.
	GetCommTimeouts (comPort, &timeouts);

	timeouts.ReadIntervalTimeout = 250;
	timeouts.ReadTotalTimeoutMultiplier = 1;
	timeouts.ReadTotalTimeoutConstant = 500;
	timeouts.WriteTotalTimeoutMultiplier = 1;
	timeouts.WriteTotalTimeoutConstant = 2500;

	rc = SetCommTimeouts(comPort, &timeouts);          // If the function fails, the return value is zero.
	if (rc == 0)
	{
		printf("\nSetCommTimeouts(): ");
		printf(getLastErrorText(msgTextBuf, sizeof(msgTextBuf)));
		return FALSE;
	}

	return TRUE;
}
示例#4
0
int serialGetC(HANDLE fd, uint8_t* c, int timeout)
{
	COMMTIMEOUTS timeouts;
	unsigned long res;
	COMSTAT comStat;
	DWORD errors;

	if(!ClearCommError(fd, &errors, &comStat)) {
		printErr("could not reset comm errors", GetLastError());
		return -1;
	}

	if(!GetCommTimeouts(fd, &timeouts)) {
		printErr("error getting comm timeouts", GetLastError());
		return -1;
	}
	timeouts.ReadIntervalTimeout = timeout;
	timeouts.ReadTotalTimeoutConstant = timeout;
	timeouts.ReadTotalTimeoutMultiplier = 10;
	if(!SetCommTimeouts(fd, &timeouts)) {
		printErr("error setting comm timeouts", GetLastError());
		return -1;
	}

	if(!ReadFile(fd, c, 1, &res, NULL)) {
		printErr("error reading from serial port", GetLastError());
		return -1;
	}

	if(res != 1)
		return -1;

	return *c;
}
示例#5
0
/** open a serial port */
static HANDLE openPort(const char *port,int baud)
{
	HANDLE       h;
	DCB          dcb;
	COMMTIMEOUTS tmo;
	int          status;

	/* open the port */
	h = CreateFile( port,  
                    GENERIC_READ | GENERIC_WRITE, 
                    0, 
                    0, 
                    OPEN_EXISTING,
                    0,
                    0);
	if (h == INVALID_HANDLE_VALUE) {
		/* quit on error */
		return h;
	}
   

	/* read current configuration */
   status = GetCommState(h,&dcb);
   if (status == 0) {
	   CloseHandle(h);
	   return INVALID_HANDLE_VALUE;
   }

   /* set the baud rate and other parameters */
   dcb.BaudRate = baud;
   dcb.ByteSize = 8;
   dcb.Parity   = NOPARITY; 
   dcb.StopBits = ONESTOPBIT;

   /* set configuration */
   status = SetCommState(h, &dcb);
   if (status == 0) {
	   CloseHandle(h);
	   return INVALID_HANDLE_VALUE;
   }

   /* read timeout configuration */
   status = GetCommTimeouts(h,&tmo);
   if (status == 0) {
	   CloseHandle(h);
	   return INVALID_HANDLE_VALUE;
   }

   /* set to indefinite blocking */
   tmo.ReadIntervalTimeout        = 0;
   tmo.ReadTotalTimeoutConstant   = 0;
   tmo.ReadTotalTimeoutMultiplier = 0;
   status = SetCommTimeouts(h,&tmo);
   if (status == 0) {
	   CloseHandle(h);
	   return INVALID_HANDLE_VALUE;
   }

	return h;
}
示例#6
0
文件: SerialPort.cpp 项目: berak/e6
		virtual bool setTimeout (int iTotalReadTimeout)
		{
			if (INVALID_HANDLE_VALUE == hComm)
				return (TRUE);

			if (!GetCommTimeouts(this->hComm, &timeouts_alt)) 
			{
				this->close ();
				MessageBox (NULL, "could not open comport!\nGetCommTimeouts()",
					NULL, NULL);
				return (FALSE);
			}

			COMMTIMEOUTS timeouts;
			timeouts.ReadIntervalTimeout = MAXDWORD ;
			timeouts.ReadTotalTimeoutMultiplier = MAXDWORD ;
			timeouts.ReadTotalTimeoutConstant = (DWORD) iTotalReadTimeout;
			timeouts.WriteTotalTimeoutMultiplier = 1000;
			timeouts.WriteTotalTimeoutConstant = 1000;

			if (!SetCommTimeouts(hComm, &timeouts))
				return (FALSE);

			return(TRUE);
		}
示例#7
0
/****************************************************************************
* DESCRIPTION: Initializes the RS485 hardware and variables, and starts in
*              receive mode.
* RETURN:      none
* ALGORITHM:   none
* NOTES:       none
*****************************************************************************/
void RS485_Initialize(
    void)
{
    RS485_Handle =
        CreateFile(RS485_Port_Name, GENERIC_READ | GENERIC_WRITE, 0, 0,
        OPEN_EXISTING,
        /*FILE_FLAG_OVERLAPPED */ 0,
        0);
    if (RS485_Handle == INVALID_HANDLE_VALUE) {
        fprintf(stderr, "Unable to open %s\n", RS485_Port_Name);
        RS485_Print_Error();
        exit(1);
    }
    if (!GetCommTimeouts(RS485_Handle, &RS485_Timeouts)) {
        RS485_Print_Error();
    }
    RS485_Configure_Status();
#if PRINT_ENABLED
    fprintf(stderr, "RS485 Interface: %s\n", RS485_Port_Name);
#endif

    atexit(RS485_Cleanup);

    return;
}
示例#8
0
文件: IO.cpp 项目: variantf/quadrotor
HANDLE IO::openComm() {
	h = CreateFile(TEXT("COM3"), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
	if (INVALID_HANDLE_VALUE == h) {
		int err = GetLastError();
		return h;
	}

	COMMTIMEOUTS timeouts;
	GetCommTimeouts(h, &timeouts);
	timeouts.ReadIntervalTimeout = 0;
	timeouts.ReadTotalTimeoutMultiplier = 0;
	timeouts.ReadTotalTimeoutConstant = 0;
	timeouts.WriteTotalTimeoutMultiplier = 0;
	timeouts.WriteTotalTimeoutConstant = 0;
	SetCommTimeouts(h, &timeouts);

	//设置串口配置信息
	DCB dcb;
	if (!GetCommState(h, &dcb))
	{
		cout << "GetCommState() failed" << endl;
		CloseHandle(h);
		return INVALID_HANDLE_VALUE;
	}
	int nBaud = 57600;
	dcb.DCBlength = sizeof(DCB);
	dcb.BaudRate = nBaud;//波特率为9600
	dcb.Parity = 0;//校验方式为无校验
	dcb.ByteSize = 8;//数据位为8位
	dcb.StopBits = ONESTOPBIT;//停止位为1位
	if (!SetCommState(h, &dcb))
	{
		cout << "SetCommState() failed" << endl;
		CloseHandle(h);
		return INVALID_HANDLE_VALUE;
	}

	//设置读写缓冲区大小
	static const int g_nZhenMax = 16;//32768;
	if (!SetupComm(h, g_nZhenMax, g_nZhenMax))
	{
		cout << "SetupComm() failed" << endl;
		CloseHandle(h);
		return INVALID_HANDLE_VALUE;
	}

	//清空缓冲
	PurgeComm(h, PURGE_RXCLEAR | PURGE_TXCLEAR);

	//清除错误
	DWORD dwError;
	COMSTAT cs;
	if (!ClearCommError(h, &dwError, &cs))
	{
		cout << "ClearCommError() failed" << endl;
		CloseHandle(h);
		return INVALID_HANDLE_VALUE;
	}
	return h;
}
示例#9
0
   bool CSerialLine::SetMultiplierTimeOuts( unsigned int aReadTimeOut, unsigned int aWriteTimeOut )const
   {
      TRACE_FUN( Routine, "CSerialLine::SetMultiplyTimeOuts" );

      bool ret( false );

      if( isOpen() )
      {
         #ifdef __WIN32__
            COMMTIMEOUTS commTimeOuts;

            if( GetCommTimeouts( _hFile, &commTimeOuts ) )
            {
               TraceRoutine << "commTimeOuts.ReadTotalTimeoutMultiplier: " << commTimeOuts.ReadTotalTimeoutMultiplier << std::endl;
               TraceRoutine << "commTimeOuts.WriteTotalTimeoutMultiplier: " << commTimeOuts.WriteTotalTimeoutMultiplier << std::endl;

               commTimeOuts.ReadTotalTimeoutMultiplier = aReadTimeOut;
               commTimeOuts.WriteTotalTimeoutMultiplier = aWriteTimeOut;

               ret = SetCommTimeouts( _hFile, &commTimeOuts );
            }
         #endif
      }
      return ret;
   }
示例#10
0
文件: serial.c 项目: stg/PicOptic
// configure serial port
bool sconfig(char* fmt) {
  DCB dcb;
  COMMTIMEOUTS cmt;
  // clear dcb  
  memset(&dcb,0,sizeof(DCB));
  dcb.DCBlength=sizeof(DCB);
  // configure serial parameters
  if(!BuildCommDCB(fmt,&dcb)) return false;
  dcb.fOutxCtsFlow=0;
  dcb.fOutxDsrFlow=0;
  dcb.fDtrControl=0;
  dcb.fOutX=0;
  dcb.fInX=0;
  dcb.fRtsControl=0;
  if(!SetCommState(h_serial,&dcb)) return false;
  // configure buffers
  if(!SetupComm(h_serial,1024,1024)) return false;
  // configure timeouts 
  GetCommTimeouts(h_serial,&cmt);
  memcpy(&restore,&cmt,sizeof(cmt));
  cmt.ReadIntervalTimeout=100;
  cmt.ReadTotalTimeoutMultiplier=100;
  cmt.ReadTotalTimeoutConstant=100;
  cmt.WriteTotalTimeoutConstant=100;
  cmt.WriteTotalTimeoutMultiplier=100;
  if(!SetCommTimeouts(h_serial,&cmt)) return false;
  return true;
}
示例#11
0
/**************************************************************************
 * -Name:        win_InitSerial ( port, settings )
 *
 * -Description: This routine initializes the communications port.
 *
 * -Arguments:   GIZ_PORT porttoopen - communications port to be used
 *                       GIZ_PORT_COM1 - for communications port 1
 *                       GIZ_PORT_COM2 - for communications port 2
 *               short portsettings - communications port parameters
 *                    modes are OR'd together to achieve comm port settings.
 *                    Default: GIZBAUD_9600 | GIZNONE | GIZONESTOPBIT | GIZEIGHTBITS.
 *
 *                    baud rates : GIZBAUD_300, GIZBAUD_600, GIZBAUD_1200,
 *                                 GIZBAUD_2400, GIZBAUD_4800, GIZBAUD_9600
 *
 * -Notes:       Gizzmo must have comm port settings of no parity (GIZNONE),
 *               1 stop bit (GIZONESTOPBITS), and 8 data bits (GIZEIGHTBITS).
 *               The baud rate is the only settings that can currently
 *               be varied.  To do this, please review the programmers'
 *               guide on changing the baud rate.
 *
 * -Returns : 0 if comm port setup okay
 *************************************************************************/
long  win_InitSerial ( int port )
{
	long err;
	DWORD  start,current;
    char aBuf[16];
	DWORD bytesRead;
	if((err = setup_dcb( (GIZ_PORT)(port-1), 0, (short)LINES_LOW))!=0)
		return err;
	SISetLinesLow();
	while ((current-start) < PowerOnTimeDelay) current = GetTickCount(); // PowerOnTime delay before launch to let calibrator wake up and stabilize
	
	/* create timeout data structure */
	GetCommTimeouts(PortID,&TimeOutData);
	TimeOutData.ReadIntervalTimeout = 2500;// millisecs between characters
	TimeOutData.ReadTotalTimeoutMultiplier = 250;	// millisec multiplier by number of characters
	TimeOutData.ReadTotalTimeoutConstant = 2500; // 2.5 sec + nchar * 250 msec total time out(about 3secs);
	TimeOutData.WriteTotalTimeoutMultiplier = 250;
	TimeOutData.WriteTotalTimeoutConstant = 250;
	SetCommTimeouts(PortID,&TimeOutData);
	start = GetTickCount();
	current = GetTickCount();
	SISetLinesHigh();
	while ((current-start) < PowerOnTimeDelay) current = GetTickCount(); // PowerOnTime delay before launch to let calibrator wake up and stabilize
	
	ReadFile(
		PortID,		// handle of file to read 
		aBuf,		// address of buffer that receives data  
		1,			// number of bytes to read: the count byte and the command byte
		&bytesRead,	// address of number of bytes read 
		NULL 		// address of structure for data 
	);
   	return (err);
}
示例#12
0
ComPort::ComPort(wchar_t *portName, unsigned int baund)
{
    hCOM = CreateFileW(portName,
                       GENERIC_READ | GENERIC_WRITE,
                       0,  NULL, OPEN_EXISTING,  0,  NULL);

    if(hCOM == INVALID_HANDLE_VALUE)
        throw std::runtime_error ("Unable to open port ");
    DCB dcb={0};
    COMMTIMEOUTS CommTimeouts;
    dcb.DCBlength = sizeof(DCB);
    GetCommState(hCOM, &dcb);

    dcb.BaudRate = CBR_115200;
    dcb.ByteSize = 8;
    dcb.Parity = NOPARITY;
    dcb.StopBits = ONESTOPBIT;
    SetCommState(hCOM, &dcb);

    GetCommTimeouts(hCOM,&CommTimeouts);
    CommTimeouts.ReadIntervalTimeout = 100;
    CommTimeouts.ReadTotalTimeoutMultiplier = 1;
    CommTimeouts.ReadTotalTimeoutConstant = 100;
    CommTimeouts.WriteTotalTimeoutMultiplier = 0;
    CommTimeouts.WriteTotalTimeoutConstant = 0;
    SetCommTimeouts(hCOM,&CommTimeouts);
    FlushFileBuffers(hCOM);
    DWORD Errors;
    COMSTAT ComState;
    ClearCommError(hCOM, &Errors, &ComState);
}
//---------------------------------------------------------------------------
void __fastcall TCommThread::Open()
{
        if(Connected==false)
        {
                //Open device
                DeviceHandle=CreateFile(        DeviceName.c_str(),
                                                GENERIC_READ|GENERIC_WRITE,
                                                FILE_SHARE_DELETE,
                                                NULL,
                                                OPEN_EXISTING,
                                                FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE,
                                                NULL
                                        );

                if(DeviceHandle!=INVALID_HANDLE_VALUE)
                {
                        //Make backup and set DCB of open device
                        GetCommState(DeviceHandle,&OriginalDCB);
                        SetCommState(DeviceHandle,&MyDCB);

                        //Make backup and set COMMTIMEOUTS of open device
                        GetCommTimeouts(DeviceHandle,&OriginalTimeouts);
                        SetCommTimeouts(DeviceHandle,&MyTimeouts);

                        SetupComm(DeviceHandle,1024*ReceiveQueue,1024*TransmitQueue);

                        //Resume Thread
                        if(this->Suspended)
                                Resume();
                        Connected=true;
                }//if
        }//if
}
示例#14
0
static SERIALPORT *serial_open(const char *device){
    HANDLE fh;
    DCB dcb={sizeof(DCB)};
    COMMTIMEOUTS timeouts;
    SERIALPORT *port;

    fh = CreateFile(device,GENERIC_READ|GENERIC_WRITE,0,NULL,
      OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
    if (!fh) return NULL;

    port = malloc(sizeof(SERIALPORT));
    ZeroMemory(port, sizeof(SERIALPORT));
    port->fh = fh;

    /* save current port settings */
    GetCommState(fh,&port->dcb_save);
    GetCommTimeouts(fh,&port->timeouts_save);

    dcb.DCBlength=sizeof(DCB);
    BuildCommDCB("96,n,8,1",&dcb);
    SetCommState(fh,&dcb);

    ZeroMemory(&timeouts,sizeof(timeouts));
    timeouts.ReadTotalTimeoutConstant=1;
    timeouts.WriteTotalTimeoutConstant=1;
    SetCommTimeouts(fh,&timeouts);

    serial_flush(port);

    return port;
}
示例#15
0
BOOL CPSerialPort::OpenPort(LPCTSTR Port,int BaudRate,int StopBits,int Parity,int DataBits,LPDataArriveProc proc,DWORD userdata)
{
	m_lpDataArriveProc=proc;
	m_dwUserData=userdata;

	if(m_hComm==INVALID_HANDLE_VALUE)
	{
		m_hComm=CreateFile(Port,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
		if(m_hComm==INVALID_HANDLE_VALUE )
		{
//			AfxMessageBox(_T("ERROR 104:无法打开端口!请检查是否已被占用。"));
			return FALSE;
		}
		GetCommState(m_hComm,&dcb);
		dcb.BaudRate=BaudRate;
		dcb.ByteSize=DataBits;
		dcb.Parity=Parity;
		dcb.StopBits=StopBits;
		dcb.fParity=FALSE;
		dcb.fBinary=TRUE;
		dcb.fDtrControl=0;
		dcb.fRtsControl=0;
		dcb.fOutX=dcb.fInX=dcb.fTXContinueOnXoff=0;
		
		//设置状态参数
		SetCommMask(m_hComm,EV_RXCHAR);		
		SetupComm(m_hComm,1024,1024);		
		if(!SetCommState(m_hComm,&dcb))
		{
			AfxMessageBox(_T("ERROR 105:无法按当前参数配置端口,请检查参数!"));
			PurgeComm(m_hComm,PURGE_TXCLEAR|PURGE_RXCLEAR);
			ClosePort();
			return FALSE;
		}
		
		//设置超时参数
		GetCommTimeouts(m_hComm,&CommTimeOuts);		
		CommTimeOuts.ReadIntervalTimeout=100;
		CommTimeOuts.ReadTotalTimeoutMultiplier=1;
		CommTimeOuts.ReadTotalTimeoutConstant=100;
		CommTimeOuts.WriteTotalTimeoutMultiplier=1;
		CommTimeOuts.WriteTotalTimeoutConstant=100;		
		if(!SetCommTimeouts(m_hComm,&CommTimeOuts))
		{
			AfxMessageBox(_T("ERROR 106:无法设置超时参数!"));
			PurgeComm(m_hComm,PURGE_TXCLEAR|PURGE_RXCLEAR);
			ClosePort();
			return FALSE;
		}
		
		PurgeComm(m_hComm,PURGE_TXCLEAR|PURGE_RXCLEAR);		
		Activate();
		return TRUE;		
	}
	
	return TRUE;
}
示例#16
0
文件: metrotrk.cpp 项目: nealey/vera
//-------------------------------------------------------------------------
// Initialize TRK connection over a serial port.
// Returns success.
bool metrotrk_t::init(int port)
{
  sseq = 0;

  if ( port == DEBUGGER_PORT_NUMBER )
  {
    int p = find_smartphone_port();
    if ( p > 0 )
    {
      port = p;
      msg("Using COM%d: to communicate with the smartphone...\n", port);
    }
    else
    {
      warning("Could not autodetect the smartphone port.\n"
              "Please specify it manually in the process options");
    }
  }

  char name[32];
  qsnprintf(name, sizeof(name), "\\\\.\\COM%d", port);

  qstring friendly_name;
  if ( !is_serial_port_present(port, &friendly_name) )
  {
      if ( askyn_c(0,
                   "HIDECANCEL\n"
                   "Serial port COM%d seems to be unavailable. Do you want to proceed?",
                   port ) <= 0 )
      {
        SetLastError(ERROR_DEVICE_NOT_CONNECTED);
        return false;
      }
  }
  msg("Opening serial port %s: (%s)...\n", &name[4], friendly_name.c_str());

  // port exists, open it
  hp = CreateFile(name, GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
  if ( hp == INVALID_HANDLE_VALUE )
    return false;
  DCB dcb;
  memset(&dcb, 0, sizeof(dcb));
  dcb.DCBlength = sizeof(dcb);
  dcb.BaudRate = CBR_115200;
  dcb.fBinary = true;
  dcb.ByteSize = 8;
  dcb.Parity = NOPARITY;
  dcb.StopBits = ONESTOPBIT;
  if ( !SetCommState(hp, &dcb) )
  {
    CloseHandle(hp);
    return false;
  }
  GetCommTimeouts(hp, &ct);
  return true;
}
示例#17
0
void CSerialPort::GetTimeouts(COMMTIMEOUTS& timeouts)
{
  ASSERT(IsOpen());

  if (!GetCommTimeouts(m_hComm, &timeouts))
  {
    TRACE(_T("Failed in call to GetCommTimeouts\n"));
    AfxThrowSerialException();
  }
}
vpr::Uint32 SerialPortImplWin32::read_i(void* buffer, const vpr::Uint32 length,
                                        const vpr::Interval& timeout)
{
   unsigned long bytes;

   // Shouldn't be setting this every read, but don't have any other way of
   // specifying the timeout.
   if ( vpr::Interval::NoTimeout != timeout )
   {
      COMMTIMEOUTS t;
      GetCommTimeouts(mHandle, &t);
      t.ReadTotalTimeoutConstant = (int)timeout.msec();
      SetCommTimeouts(mHandle, &t);
   }

   if ( ! ReadFile(mHandle, buffer, length, &bytes, NULL) )
   {
      std::stringstream msg_stream;
      msg_stream << "Failed to read from serial port " << mName << ": "
                 << getErrorMessageWithCode(GetLastError());
      throw IOException(msg_stream.str(), VPR_LOCATION);
   }

   //Now set the timeout back
   if ( vpr::Interval::NoTimeout != timeout )
   {
      COMMTIMEOUTS t;
      GetCommTimeouts(mHandle, &t);
      t.ReadTotalTimeoutConstant = (int)mCurrentTimeout*100;
      SetCommTimeouts(mHandle, &t);
   }

   // XXX: Does reading 0 bytes really indicate a timeout?
   if ( bytes == 0 )
   {
      std::stringstream msg_stream;
      msg_stream << "Timeout while attempting to read from serial port "
                 << mName;
      throw TimeoutException(msg_stream.str(), VPR_LOCATION);
   }

   return bytes;
}
示例#19
0
static void set_timeout(urg_serial_t *serial, int timeout)
{
    COMMTIMEOUTS timeouts;
    GetCommTimeouts(serial->hCom, &timeouts);

    timeouts.ReadIntervalTimeout = (timeout == 0) ? MAXDWORD : 0;
    timeouts.ReadTotalTimeoutConstant = timeout;
    timeouts.ReadTotalTimeoutMultiplier = 0;

    SetCommTimeouts(serial->hCom, &timeouts);
}
示例#20
0
/*----------------------------------------------------------------------------*/
int serial_read(int fd, void *buffer, unsigned size, unsigned timeout)
{
  HANDLE h;
  COMMTIMEOUTS ct;
  int received = 0;

  h = get_h(fd);
  if(!h)
    return 0;

  if(!GetCommTimeouts(h,&ct))
  {
    err_trace(__FILE__, __LINE__);
    return 0;
  }

  ct.ReadIntervalTimeout = MAXDWORD;
  ct.ReadTotalTimeoutMultiplier = MAXDWORD;
  ct.ReadTotalTimeoutConstant = timeout;

  if(!SetCommTimeouts(h,&ct))
  {
    err_trace(__FILE__, __LINE__);
    return 0;
  }

  if(!ReadFile(h, buffer, size, (DWORD *)&received, NULL))
  {
    DWORD Err;
    err_trace(__FILE__, __LINE__);
    ClearCommBreak(h);
    ClearCommError(h, &Err, NULL);
    return 0;
  }

#ifdef DEBUG
  if(!received)
  {
//    err_trace(__FILE__, __LINE__);
//    TRACE("%s:%d: Timeout reached. Timeout: %u\n", __FILE__, __LINE__, timeout );
  }
	else
	{
		int i;
		fprintf(stderr, "rx: ");
		for(i = 0; i < received; i++)
			fprintf(stderr, "%02x ", (unsigned)((char *)buffer)[i] & 0xff);
		fprintf(stderr, "\n");
	}
#endif

  return received;
}
示例#21
0
BOOL CECGDlg::OpenPort(LPCTSTR Port, int BaudRate, int DataBits, int Parity, int StopBits, HANDLE &hComm)
{
    DCB dcb;
	BOOL ret;
    COMMTIMEOUTS CommTimeOuts;
	hComm = CreateFile(Port, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
    if(hComm == INVALID_HANDLE_VALUE)
    {
		UpdateStatus(L"Unable to open the serial port or the serial port has already been opened! Please check if the port is already in use", ADDSTR2STATUS);
        return FALSE;
    }
	
    dcb.DCBlength = sizeof (dcb);
	ret = GetCommState(hComm, &dcb);
	if( !ret)
	{
		UpdateStatus(L"Unable to get Comm. State", ADDSTR2STATUS);
		ClosePort(hComm);
		return FALSE;
	}
    dcb.BaudRate = BaudRate;
    dcb.fParity = FALSE;    // Parity check disabled
    dcb.fNull = FALSE;
    dcb.ByteSize = DataBits;
    dcb.Parity = Parity;
    dcb.StopBits = StopBits;

	ret = SetCommState(hComm, &dcb);
    if( !ret )
    {
		UpdateStatus(L"Unable to configure serial port. Please check the port configuration! Serial port is closed", ADDSTR2STATUS);
        ClosePort(hComm);
        return FALSE;
    }

    GetCommTimeouts(hComm, &CommTimeOuts);
    CommTimeOuts.ReadIntervalTimeout = 100;      // Max text receiving interval
    CommTimeOuts.ReadTotalTimeoutMultiplier = 1;
    CommTimeOuts.ReadTotalTimeoutConstant = 100; // Number of timeouts for reading data
    CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
    CommTimeOuts.WriteTotalTimeoutConstant = 0;
	ret = SetCommTimeouts(hComm, &CommTimeOuts);
    if ( !ret )
    {
		UpdateStatus(L"Unable to set timeout parameter! Serial port is closed!", ADDSTR2STATUS);
        ClosePort(hComm);
        return FALSE;
    }

    PurgeComm(hComm, PURGE_TXCLEAR | PURGE_RXCLEAR);

	return TRUE;
}
示例#22
0
bool Serial::Open()
{
	if (_file)
		return false;

	std::wstring path = L"\\\\.\\";
	path += GetPortName();
		
	HANDLE file = CreateFile(path.c_str(), GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr);
	if (!file || file == INVALID_HANDLE_VALUE)
	{
		AfxMessageBox(L"CreateFile failed");
		return false;
	}
	DCB dcb;
	::memset(&dcb, 0, sizeof dcb);
	dcb.fBinary = true;
	dcb.BaudRate = UsbSpeed;
	dcb.ByteSize = 8;
	if (!SetCommState(file, &dcb))
	{
		AfxMessageBox(L"SetCommState failed");
		return false;
	}

	COMMTIMEOUTS timeouts;
	if (!GetCommTimeouts(file, &timeouts))
	{
		AfxMessageBox(L"GetCommTimeouts failed");
		return false;
	}

	//timeouts.ReadIntervalTimeout = 5;
	//timeouts.ReadTotalTimeoutConstant = 5;
	//timeouts.ReadTotalTimeoutMultiplier = 10;

	timeouts.ReadIntervalTimeout = 1;
	timeouts.ReadTotalTimeoutConstant = 1;
	timeouts.ReadTotalTimeoutMultiplier = 1;

	if (!SetCommTimeouts(file, &timeouts))
	{
		AfxMessageBox(L"SetCommTimeouts failed");
		return false;
	}

	_file = file;
	_abort = false;
	_thread = std::thread(&Serial::Go, this);

	return true;
}
示例#23
0
DWORD __stdcall ConfigSerialPort(HANDLE h, DWORD dwBaudRate, DWORD dwTimeOutInSec)
{
	if (!SetupComm(h, 1024, 1024))
	{
		return ::GetLastError();
	}

	DCB dcbConfig;

	if (GetCommState(h, &dcbConfig)) /* Configuring Serial Port Settings */
	{
		dcbConfig.BaudRate = dwBaudRate;
		dcbConfig.ByteSize = 8;
		dcbConfig.Parity = NOPARITY;
		dcbConfig.StopBits = ONESTOPBIT;
		dcbConfig.fBinary = TRUE;
		dcbConfig.fParity = TRUE;
	}
	else
	{
		return ::GetLastError();
	}

	if (!SetCommState(h, &dcbConfig))
	{
		return ::GetLastError();
	}

	COMMTIMEOUTS commTimeout;

	if (GetCommTimeouts(h, &commTimeout)) /* Configuring Read & Write Time Outs */
	{
		commTimeout.ReadIntervalTimeout = 1000 * dwTimeOutInSec;
		commTimeout.ReadTotalTimeoutConstant = 1000 * dwTimeOutInSec;
		commTimeout.ReadTotalTimeoutMultiplier = 0;
		commTimeout.WriteTotalTimeoutConstant = 1000 * dwTimeOutInSec;
		commTimeout.WriteTotalTimeoutMultiplier = 0;
	}
	else
	{
		return ::GetLastError();
	}

	if (SetCommTimeouts(h, &commTimeout))
	{
		return ERROR_SUCCESS;
	}
	else
	{
		return ::GetLastError();
	}
}
示例#24
0
/* device control settings */
unsigned int term_set_control ( unsigned int baud, unsigned char databits, unsigned char stopbits, unsigned char parity, unsigned char handshake )
{
    /*
        todo:
            - error checking
            - handshake
            - parity
            - stopbits
            - let the user configure timeouts ?
    */

    COMMCONFIG lpCC;
    COMMTIMEOUTS timeouts;

    if ( !hCom )
    {
        printf ( "%s: COM port was not open!\n", __FUNCTION__ );
        return RXE_FAIL;
    }

    GetCommTimeouts ( hCom, &timeouts );
    
	// TODO
	timeouts.ReadIntervalTimeout = 1;
    timeouts.ReadTotalTimeoutMultiplier = 0; 
    timeouts.ReadTotalTimeoutConstant = 10;
    timeouts.WriteTotalTimeoutMultiplier = 0;
    timeouts.WriteTotalTimeoutConstant = 10;

	if ( !SetCommTimeouts ( hCom, &timeouts ) )
    {
        printf ( "%s: setting timeouts didn't work!\n", __FUNCTION__ );
        return RXE_FAIL;
    }


	GetCommState ( hCom, &lpCC.dcb );

	lpCC.dcb.BaudRate = baud ? baud: CBR_115200;
    lpCC.dcb.ByteSize = databits;
    lpCC.dcb.StopBits = ONESTOPBIT;
    lpCC.dcb.Parity = NOPARITY;

    lpCC.dcb.fDtrControl = DTR_CONTROL_DISABLE;
    lpCC.dcb.fRtsControl = RTS_CONTROL_DISABLE;
    
	SetCommState ( hCom, &lpCC.dcb );

	return RXE_OK;
}
示例#25
0
// Set Rx Timeout in ms
// Timeout: Rx receive timeout in ms
// return: last set Rx timeout or -1 on error
int ComPort::SetRxTimeout(int Timeout)
{
  COMMTIMEOUTS CommTimeouts;
  int result;
  DWORD dwError;

  if (hPort == INVALID_HANDLE_VALUE)
    return -1;

  GetCommTimeouts(hPort, &CommTimeouts);

  result = CommTimeouts.ReadTotalTimeoutConstant;
  
  // Change the COMMTIMEOUTS structure settings.
  CommTimeouts.ReadIntervalTimeout = MAXDWORD;

  // JMW 20070515
  if (Timeout == 0) {
    // no total timeouts used
    CommTimeouts.ReadTotalTimeoutMultiplier = 0; 
    CommTimeouts.ReadTotalTimeoutConstant = 0;
  } else {
    // only total timeout used
    CommTimeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
    CommTimeouts.ReadTotalTimeoutConstant = Timeout;
  }

  CommTimeouts.WriteTotalTimeoutMultiplier = 10;  
  CommTimeouts.WriteTotalTimeoutConstant = 1000;    

                                        // Set the time-out parameters
                                        // for all read and write
                                        // operations on the port.
  if (!SetCommTimeouts(hPort, &CommTimeouts)) {
     // Could not create the read thread.
    CloseHandle(hPort);
    hPort = INVALID_HANDLE_VALUE;
#if (WINDOWSPC>0) || NEWCOMM // 091206
    Sleep(2000); // needed for windows bug
#endif
    ComPort_StatusMessage(MB_OK, TEXT("Error"), TEXT("%s %s"),
	// LKTOKEN  _@M760_ = "Unable to Set Serial Port Timers" 
                 gettext(TEXT("_@M760_")), sPortName);
    dwError = GetLastError();
    return -1;
  }

  return result;
}
示例#26
0
EXPORT int serial_comm_set_settings(void *handle, SERIAL_COM_SETTINGS * settings)
{
    BOOL port_ready;
    DCB comm_state;
    COMMTIMEOUTS timeouts;

    if(handle == NULL)
        return RESULT_FAILURE;

    port_ready = SetupComm(handle, settings->InputBufferSize, settings->OutputBufferSize);

    if(!port_ready)
        return RESULT_FAILURE;

    port_ready = GetCommState(handle, &comm_state);

    if(!port_ready)
        return RESULT_FAILURE;

    comm_state.BaudRate = settings->Baud;
    comm_state.ByteSize = settings->ByteSize;
    comm_state.Parity = settings->Parity;
    comm_state.StopBits = settings->StopBits;
    comm_state.fAbortOnError = settings->AbortOnError;

    port_ready = SetCommState(handle, &comm_state);

    if(!port_ready)
        return RESULT_FAILURE;

    port_ready = GetCommTimeouts (handle, &timeouts);

    if(!port_ready)
        return RESULT_FAILURE;

    timeouts.ReadIntervalTimeout = settings->ReadIntervalTimeout;
    timeouts.ReadTotalTimeoutConstant = settings->ReadTotalTimeoutConstant;
    timeouts.ReadTotalTimeoutMultiplier = settings->ReadTotalTimeoutMultiplier;
    timeouts.WriteTotalTimeoutConstant = settings->WriteTotalTimeoutConstant;
    timeouts.WriteTotalTimeoutMultiplier = settings->WriteTotalTimeoutMulitplier;

    port_ready = SetCommTimeouts (handle, &timeouts);

    if(!port_ready)
        return RESULT_FAILURE;


    return RESULT_SUCCESS;
}
示例#27
0
void win_SetTimeOut(double dataInSecs)
{


  GetCommTimeouts(PortID,&TimeOutData);
	
	TimeOutData.ReadTotalTimeoutConstant = short(dataInSecs * 1000) + 500; // 2.5 sec + nchar * 250 msec total time out(about 3secs);
	
	SetCommTimeouts(PortID,&TimeOutData);





}
示例#28
0
/* Open the communication channel */
void SerialPort::openChannel()
{
	char comName[] = "COMx";
	COMMTIMEOUTS comTimeouts;

	/* Check if channel already open */
	if( channelOpen )
		throw new ErrorMsg( "Channel already open! Cannot open port twice." );

	/* Generate COM filename and attempt open */
	comName[3] = '0' + portNumber;
	serialHandle = CreateFile( comName, GENERIC_READ | GENERIC_WRITE, 0, NULL,
			OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );

	/* Print error and return if failed opening port */
	if( serialHandle == INVALID_HANDLE_VALUE )
		throw new ErrorMsg( "Error opening COM port!" );

	channelOpen = true;

	/* Store old COM port settings */
	if( !GetCommTimeouts( serialHandle, &oldComTimeouts ) )
		throw new ErrorMsg( "Error reading COM port settings!" );

	/* Get another copy of the COM settings, and change them */
	if( !GetCommTimeouts( serialHandle, &comTimeouts ) )
		throw new ErrorMsg( "Error reading COM port settings!" );

	comTimeouts.ReadIntervalTimeout = MAXDWORD;
	comTimeouts.ReadTotalTimeoutConstant = 0;
	comTimeouts.ReadTotalTimeoutMultiplier = 0;

	/* Apply new settings */
	if( !SetCommTimeouts( serialHandle, &comTimeouts ) )
		throw new ErrorMsg( "Error changing COM port settings!" );
}
示例#29
0
void CUartChannel::SetupTimesout(void)
{
	COMMTIMEOUTS  CommTimeOuts ;

	if(this->IsOpened() == FALSE)
		return;
	if (!GetCommTimeouts(this->m_Hcomm,&CommTimeOuts))
		return;
	CommTimeOuts.ReadIntervalTimeout = 20;//MAXDWORD;//0xFFFFFFFF ;
	CommTimeOuts.ReadTotalTimeoutMultiplier = 10;//MAXDWORD;//0 ;
	CommTimeOuts.ReadTotalTimeoutConstant = 100;//MAXDWORD-1;//1000 ;
	CommTimeOuts.WriteTotalTimeoutMultiplier = 10;//2*CBR_9600/DBUG_BAUD ;
	CommTimeOuts.WriteTotalTimeoutConstant = 100 ;
	SetCommTimeouts(this->m_Hcomm, &CommTimeOuts);
}
示例#30
0
__bool CSerialPort::write_timeout(DWORD TotalTimeouts)
{
	COMMTIMEOUTS tout;
	if(INVALID_HANDLE_VALUE == m_hFile){
		SetLastError(ERROR_INVALID_HANDLE);
		return __false;
	}
	if(!GetCommTimeouts(m_hFile, &tout)){
		return __false;
	}
	tout.WriteTotalTimeoutConstant = TotalTimeouts;
	if( !SetCommTimeouts(m_hFile, &tout)){
		return __false;
	}
	return __true;
}