当前位置: 首页>>代码示例>>C++>>正文


C++ SetCommState函数代码示例

本文整理汇总了C++中SetCommState函数的典型用法代码示例。如果您正苦于以下问题:C++ SetCommState函数的具体用法?C++ SetCommState怎么用?C++ SetCommState使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了SetCommState函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: open_ifport

int open_ifport (PORTPROP *pc)
{
	OSVERSIONINFO vinfo = { sizeof(OSVERSIONINFO) };
	LARGE_INTEGER val1;
	BYTE cmdspi[6];
	static const WORD PortsCom[] = { COM1ADR, COM2ADR, COM3ADR, COM4ADR };
	static const WORD PortsLpt[] = { LPT1ADR, LPT2ADR, LPT3ADR };
	char sComm[16];
	DCB dcb = { sizeof(DCB),
				9600, TRUE, FALSE, TRUE, FALSE,
				DTR_CONTROL_DISABLE, FALSE,
				TRUE, FALSE, FALSE, FALSE, FALSE,
				RTS_CONTROL_DISABLE, FALSE, 0, 0,
				10, 10,
				8, NOPARITY, ONESTOPBIT, '\x11', '\x13', '\xFF', '\xFF', 0 };
	COMMTIMEOUTS commtimeouts = { 0, 1, 100, 1, 300};


	/* Check if high resolution timer is supported */
	QueryPerformanceFrequency(&val1);
	if (val1.QuadPart == 0) {
		pc->Info1 = "Incompatible envilonment.\n";
		return 1;
	}

	PortDly = pc->Delay;		/* I/O delay for direct I/O control */
	dcb.BaudRate = pc->Baud;	/* Bit rate for SPI bridge */

	/* Open direct I/O driver if needed */
	if(GetVersionEx(&vinfo) == FALSE) {
		pc->Info1 = "Incompatible envilonment.\n";
		return 1;
	}
	if((vinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
	    && ((pc->PortClass == TY_COMM)||(pc->PortClass == TY_LPT))) {
		if(init_driver()) {
			pc->Info1 = "I/O driver initialization failed.\n";
			return 1;
		}
	}

	/* Use COM port in direct I/O */
	if(pc->PortClass == TY_COMM) {
		if((pc->PortNum < 1)||(pc->PortNum > 4)) {
			pc->Info1 = "Invalid Port#.\n";
			return 1;
		}
		PortBase = PortsCom[pc->PortNum - 1];
		sprintf(str_info, "No COM%u(0x%X) port.\n", pc->PortNum, PortBase);
		pc->Info1 = str_info;
		if(check_comport()) {
			if(vinfo.dwPlatformId != VER_PLATFORM_WIN32_NT) return 1;
			sprintf(sComm, "\\\\.\\COM%u", pc->PortNum);
			hComm = CreateFile(sComm, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
			if(hComm == INVALID_HANDLE_VALUE) return 1;
			if(check_comport()) return 1;
		}

		_outp(COM_IMR, 0x00);		/* Mask interrupts */
		pc->Info1 = NULL;
		PortType = TY_COMM;
		return 0;
	}

	/* Use COM port via API */
	if(pc->PortClass == TY_VCOM) {
		sprintf(sComm, "\\\\.\\COM%u", pc->PortNum);
		hComm = CreateFile(sComm, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if(hComm == INVALID_HANDLE_VALUE) {
			sprintf(str_info, "%s could not be opened.\n", sComm);
			pc->Info1 = str_info;
			return 1;
		}
		SetCommState(hComm, &dcb);
		EscapeCommFunction(hComm, CLRRTS);
		EscapeCommFunction(hComm, CLRDTR);
		PortType = TY_VCOM;
		return 0;
	}

	/* Use SPI bridge attached on COM port */
	if(pc->PortClass == TY_BRIDGE) {
		sprintf(sComm, "\\\\.\\COM%u", pc->PortNum);
		hComm = CreateFile(sComm, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if(hComm == INVALID_HANDLE_VALUE) {
			sprintf(str_info, "%s could not be opened.\n", sComm);
			pc->Info1 = str_info;
			return 1;
		}
		dcb.fOutxCtsFlow = TRUE;
		dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
		SetCommState(hComm, &dcb);
		SetCommTimeouts(hComm, &commtimeouts);
		EscapeCommFunction(hComm, CLRDTR);
		delay_ms(10);
		while(read_bridge(cmdspi, sizeof(cmdspi)));
		cmdspi[0] = FLAG-1;
		cmdspi[1] = FLAG; cmdspi[2] = SPI_ENABLE;	/* Enable Bridge */
		cmdspi[3] = FLAG; cmdspi[4] = SPI_SETDLY; cmdspi[5] = (BYTE)PortDly; /* Set SPI delay */
		send_bridge(cmdspi, 6);		/* Send bridge initialization commands */
//.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:rundfunker,代码行数:101,代码来源:hwctrl.c

示例2: CreateFile


//.........这里部分代码省略.........
        case 4800:
            pd->m_oDCB.BaudRate = CBR_4800;
            break;
        case 9600:
            pd->m_oDCB.BaudRate = CBR_9600;
            break;
        case 14400:
            pd->m_oDCB.BaudRate = CBR_14400;
            break;
        case 19200:
            pd->m_oDCB.BaudRate = CBR_19200;
            break;
        case 38400:
            pd->m_oDCB.BaudRate = CBR_38400;
            break;
        case 56000:
            pd->m_oDCB.BaudRate = CBR_56000;
            break;
        case 57600:
            pd->m_oDCB.BaudRate = CBR_57600;
            break;
        case 115200:
            pd->m_oDCB.BaudRate = CBR_115200;
            break;
        case 128000:
            pd->m_oDCB.BaudRate = CBR_128000;
            break;
        case 2560000:
            pd->m_oDCB.BaudRate = CBR_256000;
            break;
        default:
            dbg_pe("UART::open Unsupport baud rate %d.", baud_rate);;
            ret_code = 3;
            goto UART_OPEN_ERR;
    }

    if( DTR_sw )
        pd->m_oDCB.fDtrControl = DTR_CONTROL_DISABLE;
    if( RTS_sw )
        pd->m_oDCB.fRtsControl = RTS_CONTROL_DISABLE;

    pd->m_oDCB.ByteSize = byte_size;
    pd->m_oDCB.Parity   = parity_sw;
    switch( stop_bits ) {
        case 1:
            pd->m_oDCB.StopBits = ONESTOPBIT;
            break;
        case 15:
            pd->m_oDCB.StopBits = ONE5STOPBITS;
            break;
        case 2:
            pd->m_oDCB.StopBits = TWOSTOPBITS;
            break;
    }

    fSuccess = SetCommState(pd->m_hCom, &(pd->m_oDCB));
    if (!fSuccess) {
        // Handle the error.
        dbg_pe("UART::open SetComState failed with error %d.", GetLastError());
        ret_code = 4;
        goto UART_OPEN_ERR;
    }

    // timout options
    if( timeout_sw ) {
        fSuccess = GetCommTimeouts(     pd->m_hCom,         /* Handle to comm device */
                                        &oComTimeout        /* time-out values */
                                  );
        if( !fSuccess ) {
            dbg_pe("UART::open GetCommTimeouts failed with error %d.", GetLastError());
            ret_code = 5;
            goto UART_OPEN_ERR;
        }

        oComTimeout.ReadIntervalTimeout         =  DEFAULT_READINTERVALTIMEOUT;
        oComTimeout.ReadTotalTimeoutMultiplier  =  DEFAULT_READMULTIPLIER;
        oComTimeout.ReadTotalTimeoutConstant    =  DEFAULT_READTOTALTIMEOUT;
        oComTimeout.WriteTotalTimeoutMultiplier =  DEFAULT_WRITEMULTIPLIER;
        oComTimeout.WriteTotalTimeoutConstant   =  DEFAULT_WRITETOTALTIMEOUT;

        fSuccess = SetCommTimeouts(     pd->m_hCom,
                                        &oComTimeout
                                  );
        if( !fSuccess ) {
            dbg_pe("UART::open SetCommTimeouts failed with error %d.", GetLastError());
            ret_code = 6;
            goto UART_OPEN_ERR;
        }
    }

    // port state
    goto UART_OPEN_RET;

UART_OPEN_ERR:
    CloseHandle(pd->m_hCom);
    pd->m_hCom = NULL;

UART_OPEN_RET:
    return ret_code;
}
开发者ID:OpenGelo,项目名称:Map2DFusion,代码行数:101,代码来源:PI_SerialPort.cpp

示例3: ndiSerialComm

int ndiSerialComm(HANDLE serial_port, int baud, const char *mode,
                 int handshake)
{
  DCB comm_settings;
  int newbaud;

  switch (baud)
    {
    case 9600:   newbaud = CBR_9600;   break;
    case 14400:  newbaud = CBR_14400;  break;
    case 19200:  newbaud = CBR_19200;  break;
    case 38400:  newbaud = CBR_38400;  break;
    case 57600:  newbaud = CBR_57600;  break;
    case 115200: newbaud = CBR_115200; break;
    default:     return -1;
    }

  GetCommState(serial_port,&comm_settings);

  comm_settings.BaudRate = newbaud;     /* speed */

  if (handshake) {                      /* set handshaking */
    comm_settings.fOutxCtsFlow = TRUE;       /* on */
    comm_settings.fRtsControl = RTS_CONTROL_HANDSHAKE;
  }
  else {
    comm_settings.fOutxCtsFlow = FALSE;       /* off */
    comm_settings.fRtsControl = RTS_CONTROL_DISABLE;
  }    

  if (mode[0] == '8') {                 /* data bits */
    comm_settings.ByteSize = 8;
  }
  else if (mode[0] == '7') {
    comm_settings.ByteSize = 7;
  }
  else {
    return -1;
  }

  if (mode[1] == 'N') {                 /* set parity */
    comm_settings.Parity = NOPARITY;
  }
  else if (mode[1] == 'O') {
    comm_settings.Parity = ODDPARITY;
  }
  else if (mode[1] == 'E') {
    comm_settings.Parity = EVENPARITY;
  }
  else {
    return -1;
  }

  if (mode[2] == '1') {                  /* set stop bits */
    comm_settings.StopBits = ONESTOPBIT;
  }
  else if (mode[2] == '2') {
    comm_settings.StopBits = TWOSTOPBITS;
  }
  else {
    return -1;
  }

  SetCommState(serial_port,&comm_settings);

  return 0;
}
开发者ID:IbisNeuronav,项目名称:Ibis,代码行数:67,代码来源:ndicapi_serial.c

示例4: xtapi_device_create_comm_object

int xtapi_device_create_comm_object(COMM_OBJ *commobj)
{
	VARSTRING *varstr = NULL;
	DWORD varstrsize;
	HANDLE hCommHandle=NULL;
	LINECALLINFO *lcinfo = NULL;
	int retval;
	int errval = XTAPI_SUCCESS;

	Assert(TapiDev.connected);

	varstrsize = sizeof(VARSTRING) + 1024;
	
	while (1)
	{
		varstr = (VARSTRING *)realloc(varstr, varstrsize);
		if (!varstr) {
			errval = XTAPI_OUT_OF_MEMORY;
			goto device_create_comm_exit;
		}

		varstr->dwTotalSize = varstrsize;

		retval = lineGetID(0,0,TapiDev.hCall, LINECALLSELECT_CALL, varstr,
						"comm/datamodem");
		errval = xtapi_err(retval);
		
		if (varstr->dwNeededSize > varstr->dwTotalSize) {
			varstrsize = varstr->dwNeededSize;
		}
		else break;
	}

	if (errval != XTAPI_SUCCESS) return errval;

	hCommHandle = *((LPHANDLE)((LPBYTE)varstr+varstr->dwStringOffset));

	lcinfo = tapi_line_getcallinfo(TapiDev.hCall);
	if (!lcinfo) {
		errval = XTAPI_OUT_OF_MEMORY;
		goto device_create_comm_exit;
	}


//	Create the COMM compatible COMM_OBJ
//	Most COMM settings will be set by TAPI, so this is less intensive than the 
//	COMM open connection
	{
		COMMTIMEOUTS ctimeouts;

		memset(commobj, 0, sizeof(COMM_OBJ));
	
		if (GetFileType(hCommHandle) != FILE_TYPE_CHAR) {
			errval = XTAPI_GENERAL_ERR;
			goto device_create_comm_exit;
		}
	
		GetCommState(hCommHandle, &commobj->dcb);
		GetCommTimeouts(hCommHandle, &ctimeouts);

		commobj->handle = hCommHandle;
		commobj->baud = lcinfo->dwRate;


//		commobj->dcb.BaudRate 		= commobj->baud;
//		commobj->dcb.fBinary			= 1;
//		commobj->dcb.fNull 			= 0;
//		commobj->dcb.ByteSize 		= 8;
//		commobj->dcb.StopBits 		= ONESTOPBIT;
//		commobj->dcb.fParity			= FALSE;
//		commobj->dcb.Parity 			= NOPARITY;
//	   commobj->dcb.XonChar 		= ASCII_XON;
//	   commobj->dcb.XoffChar 		= ASCII_XOFF;
//	   commobj->dcb.XonLim 			= 1024;
//   	commobj->dcb.XoffLim 		= 1024;
//	   commobj->dcb.EofChar 		= 0;
//	   commobj->dcb.EvtChar 		= 0;
//		commobj->dcb.fOutxDsrFlow	= FALSE;
//		commobj->dcb.fOutxCtsFlow	= FALSE;					// rts/cts off

//		commobj->dcb.fDtrControl	= DTR_CONTROL_ENABLE;// dtr=on
//		commobj->dcb.fRtsControl	= RTS_CONTROL_ENABLE;

      ctimeouts.ReadIntervalTimeout         = 250;
      ctimeouts.ReadTotalTimeoutMultiplier  = 0;
      ctimeouts.ReadTotalTimeoutConstant    = 0;
      ctimeouts.WriteTotalTimeoutMultiplier = 0;
      ctimeouts.WriteTotalTimeoutConstant   = 0;

      commobj->dcb.fAbortOnError = FALSE;

      SetCommTimeouts(hCommHandle, &ctimeouts);
      SetCommState(hCommHandle, &commobj->dcb);
	}

	memset(&commobj->rov, 0, sizeof(OVERLAPPED));
	memset(&commobj->wov, 0, sizeof(OVERLAPPED));
	commobj->rov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	if (commobj->rov.hEvent == NULL) {
		errval = XTAPI_GENERAL_ERR;
//.........这里部分代码省略.........
开发者ID:gameplayer22,项目名称:d2x-1,代码行数:101,代码来源:xtapi.c

示例5: defined

ATMO_BOOL CAtmoDmxSerialConnection::OpenConnection() {
#if defined(_ATMO_VLC_PLUGIN_)
     char *serdevice = m_pAtmoConfig->getSerialDevice();
     if(!serdevice)
        return ATMO_FALSE;
#else
     int portNummer = m_pAtmoConfig->getComport();
     m_dwLastWin32Error = 0;
	 if(portNummer < 1) return ATMO_FALSE; // make no real sense;-)
#endif

     if(!m_dmx_channels_base)
        return ATMO_FALSE;

	 CloseConnection();

#if !defined(_ATMO_VLC_PLUGIN_)
     char serdevice[16];  // com4294967295
     sprintf(serdevice,"com%d",portNummer);
#endif

#if defined(WIN32)

     m_hComport = CreateFile(serdevice, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
     if(m_hComport == INVALID_HANDLE_VALUE) {
//      we have a problem here can't open com port... somebody else may use it?
//	    m_dwLastWin32Error = GetLastError();
	    return ATMO_FALSE;
     }
     /* change serial settings (Speed, stopbits etc.) */
     DCB dcb; // für comport-parameter
     dcb.DCBlength = sizeof(DCB);
     GetCommState (m_hComport, &dcb); // ger current serialport settings
     dcb.BaudRate  = 115200;        // set speed
     dcb.ByteSize  = 8;            // set databits
     dcb.Parity    = NOPARITY;     // set parity
     dcb.StopBits  = ONESTOPBIT;   // set one stop bit
     SetCommState (m_hComport, &dcb);    // apply settings

#else

     int bconst = B115200;
     m_hComport = open(serdevice, O_RDWR |O_NOCTTY);
     if(m_hComport < 0) {
	    return ATMO_FALSE;
     }

     struct termios tio;
     memset(&tio,0,sizeof(tio));
     tio.c_cflag = (CS8 | CREAD | HUPCL | CLOCAL);
     tio.c_iflag = (INPCK | BRKINT);
     cfsetispeed(&tio, bconst);
     cfsetospeed(&tio, bconst);
     if(!tcsetattr(m_hComport, TCSANOW, &tio)) {
         tcflush(m_hComport, TCIOFLUSH);
     } else {
         // can't change parms
        close(m_hComport);
        m_hComport = -1;
        return false;
     }

#endif

     return true;
}
开发者ID:iamnpc,项目名称:myfaplayer,代码行数:66,代码来源:AtmoDmxSerialConnection.cpp

示例6: CreateFile

////////////////////////////////////////////////////////////////////////////////
/////  TCommPort::OpenCommPort()
/////
/////       scope:  TCommPort public function.
/////    purpose :  Open the comm port and configure it with the current
/////               settings.
/////       args :  void
/////    returns :  bool indicating success (true) or failure.
/////    written :  10/31/96 by H Howe
/////    remarks :  Opening a comm port in windows involves getting a handle
/////               to a port (comm 1 or 2), getting the current port properties,
/////               and changing the properties to suit your needs. Each of the
/////               steps can fail. This function bundles all of these tasks
/////               into one place.
/////    methods :  use CreateFile as described in the win32 help file. Check
/////               for errors.  Then get the DCB properties.  Our private DCB
/////               properties are then copied into the 4 major settings.
void TCommPort::OpenCommPort(void)
{
    if(m_CommOpen)   // if already open, don't bother
        return;

    // we need to get the default settings while preserving the settings
    // that we override. The DCB struct has 20 or so members. We override 4.
    // Make of copy of the settings we care about.
    DCB tempDCB;
    tempDCB.BaudRate  =  m_dcb.BaudRate;
    tempDCB.ByteSize  =  m_dcb.ByteSize;
    tempDCB.Parity    =  m_dcb.Parity;
    tempDCB.StopBits  =  m_dcb.StopBits;
    m_CommPort = "\\\\.\\" + m_CommPort;
    m_hCom = CreateFile(m_CommPort.c_str(),
                        GENERIC_READ | GENERIC_WRITE,
                        0,    /* comm devices must be opened w/exclusive-access */
                        NULL, /* no security attrs */
                        OPEN_EXISTING, /* comm devices must use OPEN_EXISTING */
                        0,    /* not overlapped I/O */
                        NULL  /* hTemplate must be NULL for comm devices */
                       );

    // If CreateFile fails, throw an exception. CreateFile will fail if the
    // port is already open, or if the com port does not exist.
    if(m_hCom == INVALID_HANDLE_VALUE)
        throw ECommError(ECommError::OPEN_ERROR);


    // Now get the DCB properties of the port we just opened
    if(!GetCommState(m_hCom,&m_dcb))
    {
        // something is hay wire, close the port and return
        CloseHandle(m_hCom);
        throw ECommError(ECommError::GETCOMMSTATE);
    }

    // dcb contains the actual port properties.  Now copy our settings into this dcb
    m_dcb.BaudRate  =  tempDCB.BaudRate;
    m_dcb.ByteSize  =  tempDCB.ByteSize;
    m_dcb.Parity    =  tempDCB.Parity;
    m_dcb.StopBits  =  tempDCB.StopBits;
    m_dcb.fRtsControl = RTS_CONTROL_DISABLE;
    m_dcb.fDtrControl = DTR_CONTROL_DISABLE;
    m_dcb.fBinary   = true;
    m_dcb.fParity   = NOPARITY;
    m_dcb.fAbortOnError = false;

    // now we can set the properties of the port with our settings.
    if(!SetCommState(m_hCom,&m_dcb))
    {
        // something is hay wire, close the port and return
        CloseHandle(m_hCom);
        throw ECommError(ECommError::SETCOMMSTATE);
    }

    // set the intial size of the transmit and receive queues. These are
    // not exposed to outside clients of the class either. Perhaps they should be?
    // I set the receive buffer to 32k, and the transmit buffer to 9k (a default).
    if(!SetupComm(m_hCom, 1024*32, 1024*9))
    {
        // something is hay wire, close the port and return
        CloseHandle(m_hCom);
        throw ECommError(ECommError::SETUPCOMM);
    }

    // These values are just default values that I determined empirically.
    // Adjust as necessary. I don't expose these to the outside because
    // most people aren't sure how they work (uhhh, like me included).
    m_TimeOuts.ReadIntervalTimeout         = 15;
    m_TimeOuts.ReadTotalTimeoutMultiplier  = 1;
    m_TimeOuts.ReadTotalTimeoutConstant    = 250;
    m_TimeOuts.WriteTotalTimeoutMultiplier = 1;
    m_TimeOuts.WriteTotalTimeoutConstant   = 250;

    if(!SetCommTimeouts(m_hCom, &m_TimeOuts))
    {
        // something is hay wire, close the port and return
        CloseHandle(m_hCom);
        throw ECommError(ECommError::SETCOMMTIMEOUTS);
    }

    // if we made it to here then success
//.........这里部分代码省略.........
开发者ID:OpenSwarm,项目名称:OpenSwarm,代码行数:101,代码来源:comm.cpp

示例7: SetupUart

/****************************************************************************
* SetupUart()
*
* This function initialises the serial port and opens it ready to send and 
* receive data.
*
* The default setup is:		(define in Uart.h)
*		COM1 9600,8,1,NOPARITY
*
* Usage for default setup:				SetupUart();		
* Or usage for specific parameters:		SetupUart("COM2",2400,8,1,NOPARITY);
*
*	Parity can be:			Bitsize can be:		
*		EVENPARITY				5 - 8
*		MARKPARITY
*		NOPARITY
*		ODDPARITY
*		SPACEPARITY
*
* Will return 0 if the function fails
******************************************************************************/
int SetupUart(int ComPortNr,int baud,int Bitsize,int StopBits,int Parity)
{
    WCHAR* Port = (WCHAR*)TEXT("COM16");
	int STOPBITS;

	if(StopBits == 1)	STOPBITS = ONESTOPBIT;
//	if(StopBits == 1.5) STOPBITS = ONE5STOPBITS;
	if(StopBits == 2)	STOPBITS = TWOSTOPBITS;

    switch(ComPortNr){
        case 1:        Port = (WCHAR*) TEXT("COM1");        break;
        case 2:        Port = (WCHAR*) TEXT("COM2");        break;
        case 3:        Port = (WCHAR*) TEXT("COM3");        break;
        case 4:        Port = (WCHAR*) TEXT("COM4");        break;
        case 5:        Port = (WCHAR*) TEXT("COM5");        break;
        case 6:        Port = (WCHAR*) TEXT("COM6");        break;
        case 7:        Port = (WCHAR*) TEXT("COM7");        break;
        case 8:        Port = (WCHAR*) TEXT("COM8");        break;
        case 9:        Port = (WCHAR*) TEXT("COM9");        break;
        case 10:        Port = (WCHAR*) TEXT("COM10");        break;
        case 11:        Port = (WCHAR*) TEXT("COM11");        break;
        case 12:        Port = (WCHAR*) TEXT("COM12");        break;
        case 13:        Port = (WCHAR*) TEXT("COM13");        break;
        case 14:        Port = (WCHAR*) TEXT("COM14");        break;
        case 15:        Port = (WCHAR*) TEXT("COM15");        break;
        case 16:        Port = (WCHAR*) TEXT("COM16");        break;
    }

    // Open the serial port.
    //hPort = CreateFile (TEXT(Port),						// Name of the port
    //hPort = CreateFile ((const WCHAR*)Port,   						// Name of the port
    hPort = CreateFile (Port,   						// Name of the port
						GENERIC_READ | GENERIC_WRITE,   // Access (read-write) mode 
						0,                                  
                        NULL,
						OPEN_EXISTING,                     
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);

	// If it fails to open the port, return 0. 
	if ( hPort == INVALID_HANDLE_VALUE ) 
	{ 
		//We failed to open!  
		return 0; 
	}   

	//Get the default port setting information. 
	GetCommState (hPort, &PortDCB); 
	// Change the settings. 
	PortDCB.BaudRate = baud;              // BAUD Rate
	PortDCB.ByteSize = Bitsize;           // Number of bits/byte, 5-8 
	PortDCB.Parity = Parity;              // 0-4=no,odd,even,mark,space 
	PortDCB.StopBits = STOPBITS;          // StopBits 
	PortDCB.fNull = 0;					  // Allow NULL Receive bytes

	// Re-configure the port with the new DCB structure. 
	if (!SetCommState (hPort, &PortDCB)) 
	{ 
		// Could not create the read thread. 
		CloseHandle(hPort);   
		return 0; 
	} 

	// Retrieve the time-out parameters for all read and write operations 
	// on the port. 
	GetCommTimeouts (hPort, &CommTimeouts); 
	memset(&CommTimeouts, 0x00, sizeof(CommTimeouts)); 
    CommTimeouts.ReadIntervalTimeout = 10;        // by³o: 10 #################
    CommTimeouts.ReadTotalTimeoutConstant = 10;   // by³o: 10 #################
	CommTimeouts.WriteTotalTimeoutConstant = 10;     

	// 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);  
		return 0; 
	} 

//.........这里部分代码省略.........
开发者ID:maciek-slon,项目名称:commontools,代码行数:101,代码来源:Uart.cpp

示例8: FT_Open

RS232::RS232(int comNum, int baudrate, int bytesize, int parity, int stopbit){


	/***********************************************************************
	//Find the com port that has been assigned to your device.
	/***********************************************************************/
	/*
	res = FT_Open(0, &fthandle);

	if (res != FT_OK){

	printf("opening failed! with error %d\n", res);

	return;
	}


	res = FT_GetComPortNumber(fthandle, &COMPORT);

	if (res != FT_OK){

	printf("get com port failed %d\n", res);

	return;
	}

	if (COMPORT == -1){

	printf("no com port installed \n");
	}

	else{
	printf("com port number is %d\n", COMPORT);

	}


	FT_Close(fthandle);
	*/

	/********************************************************/
	// Open the com port assigned to your device
	/********************************************************/

	// n = sprintf_s(COMx, "\\\\.\\COM%d", COMPORT);

	// myMutex = CreateMutex(NULL, TRUE, NULL);

	InitializeCriticalSection(&cs);
	memset(gStr, 0, 256);

	n = sprintf_s(COMx, "\\\\.\\COM%d", comNum);

	hCommPort = CreateFileA(
		COMx,
		GENERIC_READ | GENERIC_WRITE,
		0,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL
		);

	if (hCommPort == INVALID_HANDLE_VALUE)
	{

		printf("Help - failed to open\n");
		return;

	}


	printf("Hello World!\n");

	/********************************************************/
	// Configure the UART interface parameters
	/********************************************************/

	fSuccess = GetCommState(hCommPort, &dcb);


	if (!fSuccess)

	{
		printf("GetCommStateFailed \n", GetLastError());
		return;

	}

	//set parameters.

	dcb.BaudRate = baudrate;
	dcb.ByteSize = bytesize;
	dcb.Parity = parity;
	dcb.StopBits = stopbit;

	fSuccess = SetCommState(hCommPort, &dcb);


	if (!fSuccess)
//.........这里部分代码省略.........
开发者ID:Y-Aihara,项目名称:create,代码行数:101,代码来源:rs232.cpp

示例9: rtp_term_aux_open

/* SPR - was RTP_HANDLE but didn't build */
long rtp_term_aux_open(void)
{
    HANDLE hComm;
    DCB dcb;

    /* JRT */
    COMMTIMEOUTS comm_timeouts;

    hComm = CreateFile( RTP_TERM_AUX_COMM_PORT,  
                    GENERIC_READ | GENERIC_WRITE, 
                    0, 
                    0, 
                    OPEN_EXISTING,
                    FILE_FLAG_OVERLAPPED,
                    0);
    if (hComm == INVALID_HANDLE_VALUE)
    {
        rtp_term_puts("Error in opening serial comm\n");
        return -1;
    }
    if (!GetCommState(hComm, &dcb))     // get current DCB
          // Error in GetCommState
          return FALSE;

    FillMemory(&dcb, sizeof(dcb), 0);
    dcb.DCBlength = sizeof(dcb);
    if (!BuildCommDCB("baud=9600 parity=n data=8 stop=1 dtr=on rts=on", &dcb)) {   
          // Couldn't build the DCB. Usually a problem
          // with the communications specification string.
          return FALSE;
    }

    // Update DCB rate.
    //dcb.BaudRate =  RTP_TERM_AUX_BAUD_RATE;

    // Set new state.
    if (!SetCommState(hComm, &dcb))
    {
      // Error in SetCommState. Possibly a problem with the communications 
      // port handle or a problem with the DCB structure itself.
    } 

    /* JRT - Get the timeout and set it appropriately */
    rtp_memset(&comm_timeouts, 0x0, sizeof(comm_timeouts));

#define GET_COMM_TIMEOUTS 0
#if GET_COMM_TIMEOUTS
    GetCommTimeouts(hComm, &comm_timeouts);
#endif

    if (!SetCommTimeouts(hComm, &comm_timeouts))
    {
        char err_string[100];
        int error;
        
        error = GetLastError();
        rtp_sprintf(err_string,
                    "rtp_term_aux_open: SetCommTimeouts failed, error = %d\n",
                    error);
        rtp_term_puts(err_string);
        return (-1);
    }

    auxComm = (RTP_HANDLE) hComm;
    
    return (auxComm);
 
}
开发者ID:peteratebs,项目名称:webcwebbrowser,代码行数:69,代码来源:rtptermaux.c

示例10: CreateFile

/********************************************************************

  Declaration:  
  Call: 
  Input:
  Returns:
  	  
*********************************************************************/ 
void CommPort::OpenPort()
{
 
	m_bPortReady = TRUE; // everything is OK so far
  
 m_hCom = CreateFile(m_sComPort, 
		GENERIC_READ | GENERIC_WRITE,
		0, // exclusive access
		NULL, // no security
		OPEN_EXISTING,
		0, // no overlapped I/O
		NULL); // null template 

 if ((unsigned)m_hCom == HFILE_ERROR)
 {
	 char *MessageBuffer = new char[50];
     sprintf(MessageBuffer, "CommPort: %s failed to open.", m_sComPort);
	 printf(MessageBuffer);
 	 throw std::runtime_error (MessageBuffer);
	 //throw std::runtime_error ("CommPort failed to open!");
	 //delete [] MessageBuffer;
 } 

  m_bPortReady = setBufferComm(); //SetupComm(m_hCom, XX, XX);
  //m_bPortReady = SetupComm(m_hCom, 128, 128);
  //SetBaudRate(0);
	
	m_bPortReady = GetCommState(m_hCom, &m_dcb);
  // Port settings are specified in a Data Communication Block (DCB). 
  // The easiest way to initialize a DCB is to call GetCommState to fill in
  // its default values, override the values that you want to change and
  // then call SetCommState to set the values.
	m_dcb.BaudRate = m_BitRate;
	m_dcb.ByteSize = 8;
	m_dcb.Parity = NOPARITY;
	m_dcb.StopBits = ONESTOPBIT;
	m_dcb.fAbortOnError = TRUE;

	m_bPortReady = SetCommState(m_hCom, &m_dcb); 
  

	// Communication timeouts are optional but can be set similarly to DCB values:
	m_bPortReady = GetCommTimeouts (m_hCom, &m_CommTimeouts);

	m_CommTimeouts.ReadIntervalTimeout = 50;
	m_CommTimeouts.ReadTotalTimeoutConstant = 50;
	m_CommTimeouts.ReadTotalTimeoutMultiplier = 10;
	m_CommTimeouts.WriteTotalTimeoutConstant = 50;
	m_CommTimeouts.WriteTotalTimeoutMultiplier = 10;

	m_bPortReady = SetCommTimeouts (m_hCom, &m_CommTimeouts);

	// If all of these API's were successful then the port is ready for use.
	if (m_bPortReady)
	{
		printf ("Comm Port %s open successfully.\n", m_sComPort);
	}
	else
	{
	  printf ("Comm Port %s opening failed.\n", m_sComPort);
	}
}
开发者ID:MakSim345,项目名称:MS-VC08,代码行数:70,代码来源:commport.cpp

示例11: defined


//.........这里部分代码省略.........
		   case 230400: cfsetispeed(&options,B230400);
						cfsetospeed(&options,B230400);
						break;

			default:	cfsetispeed(&options,B9600);
						cfsetospeed(&options,B9600);
						ofLogError("ofSerial") << "setup(): cannot set " << baud << " bps, setting to 9600";
						break;
		}

		options.c_cflag |= (CLOCAL | CREAD);
		options.c_cflag &= ~PARENB;
		options.c_cflag &= ~CSTOPB;
		options.c_cflag &= ~CSIZE;
		options.c_cflag |= CS8;
		tcsetattr(fd,TCSANOW,&options);

		bInited = true;
		ofLogNotice("ofSerial") << "opened " << portName << " sucessfully @ " << baud << " bps";

	    return true;
	//---------------------------------------------
    #endif
    //---------------------------------------------


    //---------------------------------------------
	#ifdef TARGET_WIN32
	//---------------------------------------------

	char pn[sizeof(portName)];
	int num;
	if (sscanf(portName.c_str(), "COM%d", &num) == 1) {
		// Microsoft KB115831 a.k.a if COM > COM9 you have to use a different
		// syntax
		sprintf(pn, "\\\\.\\COM%d", num);
	} else {
		strncpy(pn, (const char *)portName.c_str(), sizeof(portName)-1);
	}

	// open the serial port:
	// "COM4", etc...

	hComm=CreateFileA(pn,GENERIC_READ|GENERIC_WRITE,0,0,
					OPEN_EXISTING,0,0);

	if(hComm==INVALID_HANDLE_VALUE){
		ofLogError("ofSerial") << "setup(): unable to open " << portName;
		return false;
	}


	// now try the settings:
	COMMCONFIG cfg;
	DWORD cfgSize;
	char  buf[80];

	cfgSize=sizeof(cfg);
	GetCommConfig(hComm,&cfg,&cfgSize);
	int bps = baud;
	sprintf(buf,"baud=%d parity=N data=8 stop=1",bps);

	#if (_MSC_VER)       // microsoft visual studio
		// msvc doesn't like BuildCommDCB,
		//so we need to use this version: BuildCommDCBA
		if(!BuildCommDCBA(buf,&cfg.dcb)){
			ofLogError("ofSerial") << "setup(): unable to build comm dcb, (" << buf << ")";
		}
	#else
		if(!BuildCommDCB(buf,&cfg.dcb)){
			ofLogError("ofSerial") << "setup(): unable to build comm dcb, (" << buf << ")";
		}
	#endif


	// Set baudrate and bits etc.
	// Note that BuildCommDCB() clears XON/XOFF and hardware control by default

	if(!SetCommState(hComm,&cfg.dcb)){
		ofLogError("ofSerial") << "setup(): couldn't set comm state: " << cfg.dcb.BaudRate << " bps, xio " << cfg.dcb.fInX << "/" << cfg.dcb.fOutX;;
	}
	//ofLogNotice("ofSerial") << "bps=" << cfg.dcb.BaudRate << ", xio=" << cfg.dcb.fInX << "/" << cfg.dcb.fOutX;

	// Set communication timeouts (NT)
	COMMTIMEOUTS tOut;
	GetCommTimeouts(hComm,&oldTimeout);
	tOut = oldTimeout;
	// Make timeout so that:
	// - return immediately with buffered characters
	tOut.ReadIntervalTimeout=MAXDWORD;
	tOut.ReadTotalTimeoutMultiplier=0;
	tOut.ReadTotalTimeoutConstant=0;
	SetCommTimeouts(hComm,&tOut);

	bInited = true;
	return true;
	//---------------------------------------------
	#endif
	//---------------------------------------------
}
开发者ID:BenVanCitters,项目名称:openFrameworks,代码行数:101,代码来源:ofSerial.cpp

示例12: EIO_Open

void EIO_Open(uv_work_t* req) {
  OpenBaton* data = static_cast<OpenBaton*>(req->data);

  HANDLE file = CreateFile(
    data->path,
    GENERIC_READ | GENERIC_WRITE,
    0,
    NULL,
    OPEN_EXISTING,
    FILE_FLAG_OVERLAPPED,
    NULL);
  if (file == INVALID_HANDLE_VALUE) {
    DWORD errorCode = GetLastError();
    char temp[100];
    sprintf(temp, "Opening %s", data->path);
    ErrorCodeToString(temp, errorCode, data->errorString);
    return;
  }

  bufferSize = data->bufferSize;
  if(bufferSize > MAX_BUFFER_SIZE) {
    bufferSize = MAX_BUFFER_SIZE;
  }

  DCB dcb = { 0 };
  dcb.DCBlength = sizeof(DCB);
  if(!BuildCommDCB("9600,n,8,1", &dcb)) {
    ErrorCodeToString("BuildCommDCB", GetLastError(), data->errorString);
    return;
  }

  dcb.fBinary = true;
  dcb.BaudRate = data->baudRate;
  dcb.ByteSize = data->dataBits;
  switch(data->parity) {
  case SERIALPORT_PARITY_NONE:
    dcb.Parity = NOPARITY;
    break;
  case SERIALPORT_PARITY_MARK:
    dcb.Parity = MARKPARITY;
    break;
  case SERIALPORT_PARITY_EVEN:
    dcb.Parity = EVENPARITY;
    break;
  case SERIALPORT_PARITY_ODD:
    dcb.Parity = ODDPARITY;
    break;
  case SERIALPORT_PARITY_SPACE:
    dcb.Parity = SPACEPARITY;
    break;
  }
  switch(data->stopBits) {
  case SERIALPORT_STOPBITS_ONE:
    dcb.StopBits = ONESTOPBIT;
    break;
  case SERIALPORT_STOPBITS_ONE_FIVE:
    dcb.StopBits = ONE5STOPBITS;
    break;
  case SERIALPORT_STOPBITS_TWO:
    dcb.StopBits = TWOSTOPBITS;
    break;
  }

  if(!SetCommState(file, &dcb)) {
    ErrorCodeToString("SetCommState", GetLastError(), data->errorString);
    return;
  }

  // Set the com port read/write timeouts
  DWORD serialBitsPerByte = 8/*std data bits*/ + 1/*start bit*/;
  serialBitsPerByte += (data->parity   == SERIALPORT_PARITY_NONE ) ? 0 : 1;
  serialBitsPerByte += (data->stopBits == SERIALPORT_STOPBITS_ONE) ? 1 : 2;
  DWORD msPerByte = (data->baudRate > 0) ?
                    ((1000 * serialBitsPerByte + data->baudRate - 1) / data->baudRate) :
                    1;
  if (msPerByte < 1) {
    msPerByte = 1;
  }
  COMMTIMEOUTS commTimeouts = {0};
  commTimeouts.ReadIntervalTimeout = msPerByte; // Minimize chance of concatenating of separate serial port packets on read
  commTimeouts.ReadTotalTimeoutMultiplier  = 0; // Do not allow big read timeout when big read buffer used
  commTimeouts.ReadTotalTimeoutConstant    = 1000; // Total read timeout (period of read loop)
  commTimeouts.WriteTotalTimeoutConstant   = 1000; // Const part of write timeout
  commTimeouts.WriteTotalTimeoutMultiplier = msPerByte; // Variable part of write timeout (per byte)
  if(!SetCommTimeouts(file, &commTimeouts)) {
    ErrorCodeToString("SetCommTimeouts", GetLastError(), data->errorString);
    return;
  }

  // Remove garbage data in RX/TX queues
  PurgeComm(file, PURGE_RXCLEAR); 
  PurgeComm(file, PURGE_TXCLEAR);

  data->result = (int)file;
}
开发者ID:BrianAdams,项目名称:node-serialport,代码行数:95,代码来源:serialport_win.cpp

示例13: ComSetDCB

/** Set information specific to the serial driver device control block.
 *  @param	hc	Maximus communication handle to update
 *  @pdcb [out]		The DCB we're associating with the underlying COMMHANDLE.
 *  @returns		TRUE on success.
 */ 
USHORT COMMAPI ComSetDCB(HCOMM hc, LPDCB pdcb)
{
  return hc ? SetCommState(ComGetHandle(hc), pdcb) : FALSE;
}
开发者ID:klamonte,项目名称:maximus,代码行数:9,代码来源:ipcomm.c

示例14: IpComIsOnline


//.........这里部分代码省略.........
    FD_ZERO(&wfds);
    FD_SET(unixfd(hc), &rfds);
    FD_SET(unixfd(hc), &wfds);

    tv.tv_sec = 0;
    tv.tv_usec = 0;

    if (((rready = select(unixfd(hc) + 1, &rfds, NULL, NULL, &tv)) < 0) || (select(unixfd(hc) + 1, NULL, &wfds, NULL, &tv) < 0))
    {
      hc->fDCD = FALSE;
      shutdown(unixfd(hc), 2);
      close(unixfd(hc));      
      unlink(lockpath);
    }

    if ((rready == 1) && hc->fDCD && (hc->peekHack == -1))
    {
      unsigned char 	buf[1];
      ssize_t		i;

      i = read(unixfd(hc), &buf, 1);
      switch(i)
      {
	case 0:
	case -1:
	  hc->fDCD = FALSE;
	  shutdown(unixfd(hc), 20);
	  close(unixfd(hc));
	  break;
	case 1:
	  hc->peekHack = buf[0];
	  break;
      }

      if (hc->fDCD == FALSE)
      {
	logit("!Caller closed TCP/IP connection (Dropped Carrier)");
      }	
    }

    skipCheck:
    return hc->fDCD ? 1 : 0;
  }

  if(hc->listenfd == -1)
    return 0;

  /* No "Carrier"? See if we can accept a connection */
  FD_ZERO(&rfds);
  FD_SET(hc->listenfd, &rfds);

  /* Will longish delay cause problems with console? */
  tv.tv_sec = 0;
  tv.tv_usec = 500000;

  if (select(hc->listenfd + 1, &rfds, NULL, NULL, &tv) > 0)
  {
    int addrSize = sizeof(*hc->saddr_p);
    int fd = -1;

    fd = accept(hc->listenfd, (struct sockaddr *)&hc->saddr_p, &addrSize);
    if (fd >= 0)
    {	
      FILE* 	f = NULL;

      /* Have accepted a socket. Close the bound socket and dump
       * the parent, so that we init can swing open a new task.
       * This technique probably won't cause us much grief, except
       * maybe on a very busy system.
       */
      /* Set accepted descriptor and other misc com parameters */
      
      f = fopen(lockpath, "w");
      fclose(f);
      
      CommHandle_setFileHandle(hc->h, fd);
      hc->fDCD = TRUE;
      hc->listenfd = -1;
      memset(&dcb, 0, sizeof(dcb));
      dcb.isTerminal = FALSE;

      dcb.fBinary	= TRUE;

      SetCommState(ComGetHandle(hc), &dcb);
      ComSetBaudRate(hc, 38400, NOPARITY, 8, ONESTOPBIT);
      _SetTimeoutBlock(hc);

      hc->burstMode = TRUE; 
      hc->burstModePending = FALSE; /* turn off nagle by default */
 
      /* Stuff a fake LF into the input stream to try and kick max 
       * into waking up faster.
       */
      hc->peekHack = '\n';

    }
  }

  return hc->fDCD ? 1 : 0;
}
开发者ID:klamonte,项目名称:maximus,代码行数:101,代码来源:ipcomm.c

示例15: run


//.........这里部分代码省略.........
            NULL,           // default security attributes
            OPEN_EXISTING,  // must use OPEN_EXISTING
            0,              // not overlapped I/O
            NULL),          // hTemplate must be NULL for comm devices
            String("COM port"));

        //IF_ZERO_THROW(SetupComm(_com, 1024, 1024));

        DCB deviceControlBlock;
        SecureZeroMemory(&deviceControlBlock, sizeof(DCB));
        IF_ZERO_THROW(GetCommState(_com, &deviceControlBlock));
        deviceControlBlock.DCBlength = sizeof(DCB);
        deviceControlBlock.BaudRate = 115200; //57600; //115200; //38400; //
        deviceControlBlock.fBinary = TRUE;
        deviceControlBlock.fParity = FALSE;
        deviceControlBlock.fOutxCtsFlow = FALSE;
        deviceControlBlock.fOutxDsrFlow = TRUE;
        //deviceControlBlock.fDtrControl = DTR_CONTROL_ENABLE;
        deviceControlBlock.fDtrControl = DTR_CONTROL_HANDSHAKE;
        deviceControlBlock.fDsrSensitivity = FALSE; //TRUE;
        deviceControlBlock.fTXContinueOnXoff = TRUE;
        deviceControlBlock.fOutX = FALSE;
        deviceControlBlock.fInX = FALSE;
        deviceControlBlock.fErrorChar = FALSE;
        deviceControlBlock.fNull = FALSE;
        deviceControlBlock.fRtsControl = RTS_CONTROL_DISABLE;
        deviceControlBlock.fAbortOnError = TRUE;
        deviceControlBlock.wReserved = 0;
        deviceControlBlock.ByteSize = 8;
        deviceControlBlock.Parity = NOPARITY;
        deviceControlBlock.StopBits = ONESTOPBIT;
        deviceControlBlock.XonChar = 17;
        deviceControlBlock.XoffChar = 19;
        IF_ZERO_THROW(SetCommState(_com, &deviceControlBlock));

        COMMTIMEOUTS timeOuts;
        SecureZeroMemory(&timeOuts, sizeof(COMMTIMEOUTS));
        timeOuts.ReadIntervalTimeout = MAXDWORD;
        timeOuts.ReadTotalTimeoutMultiplier = 0;
        timeOuts.ReadTotalTimeoutConstant = 100; //MAXDWORD;
        IF_ZERO_THROW(SetCommTimeouts(_com, &timeOuts));

        IF_ZERO_THROW(SetCommMask(_com, EV_RXCHAR));
        //IF_ZERO_THROW(ClearCommBreak(_com));
        //IF_ZERO_THROW(PurgeComm(_com, PURGE_RXCLEAR | PURGE_TXCLEAR));
        //IF_ZERO_THROW(FlushFileBuffers(_com));
        //DWORD error;
        //IF_ZERO_THROW(ClearCommError(_com, &error, NULL));

        //_com.set(CreateFile(L"run.output", GENERIC_WRITE, 0, NULL,
        //    CREATE_ALWAYS, 0, NULL));

        // When running a .com file, we need the instruction pointer to start
        // at 0x100. We do this by prepending 0x100 NOP bytes at the beginning.
        // In DOS this area would contain the Program Segment Prefix structure.
        //console.write(hex(l, 8) + "\n");

        _packet.allocate(0x101);

        Byte checksum;
        if (comFile) {
            // Send 0x100 NOPs to pad out the file so that execution starts at
            // the expected IP.
            int bytes = 0xff;
            _packet[0] = bytes;
            checksum = 0;
开发者ID:reenigne,项目名称:reenigne,代码行数:67,代码来源:run.cpp


注:本文中的SetCommState函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。