示例#1
0
int main(void)
{
	int i;

	harness_boot();
	transport = harness_openTransport();

	/* since we are multi-threaded and subject to off-chip timing
         * differences this will not be sufficient to make this test 
         * deterministic
         */
        srand(0);

	/* create all the ports */
	for (i=0; i<NUM_PORTS; i++) {
		char localName[]  = "port?" LOCAL;
		char remoteName[] = "port?" REMOTE;

		/* update the port names */
		localName[4] = remoteName[4] = '0' + i;

		/* create the receiving port */
		EMBX(CreatePort(transport, localName, &(inPort[i])));
		
		/* now create both transmission ports */
		EMBX(ConnectBlock(transport, remoteName, &(outPort[i])));
		EMBX(ConnectBlock(transport, localName,  &(outPort[i+NUM_PORTS])));
	}

	/* now create the threads that will actually run the test */
	for (i=0; i<NUM_PORTS; i++) {
		harness_createThread(workerThread, (void *) i);
	}

	/* now inject some messages into the test system (we only inject
	 * half the requested number because our partner will inject the
	 * other half)
	 */
	for (i=0; i<(NUM_INJECTED / 2); i++) {
		EMBX_VOID *message;
		message = fabricateMessage();
		assert(message);
		assert(sendMessage(message));
	}

	/* now wait for the test to run out of steam */
	harness_waitForChildren();

	/* clean up after ourselves */
	for (i=0; i<NUM_PORTS; i++) {
		EMBX(ClosePort(inPort[i]));
		EMBX(ClosePort(outPort[i]));
		EMBX(ClosePort(outPort[i+NUM_PORTS]));
	}

	printf("\n"); /* pretty printing */
	harness_shutdown();
	return 0;
}
示例#2
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;
}
示例#3
0
bool Port::OpenPort(const char* name){

	struct termios newtio;
    struct serial_struct serinfo;
	double baudrate = 1000000.0; //bps (1Mbps)
    
    ClosePort();

    if((m_Socket_fd = open(name, O_RDWR|O_NOCTTY|O_NONBLOCK)) < 0){
        printf("failed!/n");
        ClosePort();
        return false;
    }

	// You must set 38400bps!
	memset(&newtio, 0, sizeof(newtio));
    newtio.c_cflag      = B38400|CS8|CLOCAL|CREAD;
    newtio.c_iflag      = IGNPAR;
    newtio.c_oflag      = 0;
    newtio.c_lflag      = 0;
    newtio.c_cc[VTIME]  = 0;
    newtio.c_cc[VMIN]   = 0;
    tcsetattr(m_Socket_fd, TCSANOW, &newtio);


	printf("Set %.1fbps ", baudrate);

	// Set non-standard baudrate
    if(ioctl(m_Socket_fd, TIOCGSERIAL, &serinfo) < 0){
        printf("failed!/n");
        ClosePort();
        return false;
    }

    serinfo.flags &= ~ASYNC_SPD_MASK;
    serinfo.flags |= ASYNC_SPD_CUST;
    serinfo.custom_divisor = serinfo.baud_base / baudrate;
	
    if(ioctl(m_Socket_fd, TIOCSSERIAL, &serinfo) < 0)
	{
		printf("failed!/n");
        ClosePort();
        return false;
	}

	tcflush(m_Socket_fd, TCIFLUSH);

    m_ByteTransferTime = (1000.0 / baudrate) * 12.0;
	
    printf("Open port success!\n");

    return true;

}
示例#4
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;
}
示例#5
0
int main(int argc, char* argv[])
{
	long status;
	unsigned long cardType;
	unsigned long cardSN;
	BYTE userID;

	status = OpenPort(1, 9600);
	if (!status) {
		status = LinkRW();
		if (status) {
			ClosePort();
			fprintf(stderr, "Connect Fail\n");
			return -1;
		}
		fprintf(stderr, "Connect Succeed\n");
		//beepOn();

		//card polling
		while (1) {
			status = GetCardType(&cardType);
			if (!status) {
				delayMS(5);
				if (cardType == 4) { //Mifare 1
					status = mfGetCardSnr(&cardSN);
					if (status) { 
						status = mfTransKey();
						if (status) {
							status = SelectCard(cardSN);
							if (!status) {
								fprintf(stderr, "Activate Succeed\n");
								userID = getUserID(cardSN);
								fprintf(stdout, "%x", userID);
								HaltCard();
								//delayMS(3000);
								break;
							}
						}
					}
				}
			}
		}		
	}
	else {
		fprintf(stderr, "Connect Fail\n");
		return -1;
	}

	ClosePort();
	return 0;
}
示例#6
0
void CSerialPort::CloseCom()
{
	if(hSerialPort != NULL)
	{
		ClosePort(hSerialPort);//关闭端口
	}
}
示例#7
0
文件: mon_qp.cpp 项目: mingpen/OpenNT
int EndJob(PORTHANDLE hPort)
{
  PSPCB pSPCB;

  TRACE0(TEXT("--EndJob\r\n"));

  if (!ValidHandle(hPort))
  {
    return(QP_BAD_PARAMETER);
  }

  pSPCB = &SPCBTable[hPort];

  pSPCB->DeviceState.bJobPresent = FALSE;
  pSPCB->DeviceState.bManualPaused = FALSE;

  // close the port
  if (ClosePort(PORT_OWN_QP,pSPCB))
  {
    TRACE0(TEXT("--ClosePort failed\r\n"));
    return(QP_FAIL);
  }

  return(QP_SUCCESS);
}
示例#8
0
rnb_err_t
RNBSocket::Disconnect (bool save_errno)
{
    if (m_fd_from_lockdown)
        m_fd_from_lockdown = false;
    return ClosePort (m_fd, save_errno);
}
示例#9
0
STDMETHODIMP CComBus::Stop(void)
{
	// TODO: Add your implementation code here
	ExitThread();
	ClosePort();
	return S_OK;
}
示例#10
0
//析构函数
CCESeries::~CCESeries()
{
    if (m_bOpened)
    {
        //关闭串口
        ClosePort();
    }
}
CCmdHandler::~CCmdHandler()
{
#ifdef USE_TCP_NOT_SERIAL
    StopWork();
#else
    ClosePort();
#endif
    SAFEDELETEP(m_pRecvBuffer);
}
示例#12
0
void JSerialComm::Close()
{
    if( !m_bOpen ) {
        return;
    }
    m_cs.Enter();
    ClosePort();
    m_bOpen = false;
    m_cs.Leave();
}
示例#13
0
void SerialMonitor::ReOpenPort(void)
{
	bool go = true;
	if (serialPort.isOpen()) {
		go = ClosePort();
	}

	if (go) {
		 //connect (&serialPort, SIGNAL(readyRead()), this, SLOT(ReadSerialPort()));
         OpenPort();
	}
}
示例#14
0
CNTSerial::~CNTSerial ()
{
    // If the device is already closed,
    // then we don't need to do anything.
    if (m_hFile)
    {
        // Display a warning
        _RPTF0(_CRT_WARN,"CNTSerial::~CNTSerial - Serial port not closed\n");

        // Close implicitly
        ClosePort();
    }
}
示例#15
0
SerialPortBase::~SerialPortBase(void)
{
	ClosePort();
	if(pthread != NULL)
	{
//      pthread->m_bTerminated = true;
		pthread->ThreadResume();//线程恢复.
		pthread->Terminate();
		pthread->WaitFor();
		delete pthread;
		pthread = NULL;
	}
}
示例#16
0
rnb_err_t
RNBSocket::Disconnect (bool save_errno)
{
#ifdef WITH_LOCKDOWN
    if (m_fd_from_lockdown)
    {
        m_fd_from_lockdown = false;
        m_fd = -1;
        lockdown_disconnect (m_ld_conn);
        return rnb_success;
    }
#endif
    return ClosePort (m_fd, save_errno);
}
示例#17
0
// Open the communication (done when you create it)
void CCPCBooster::OpenPort()
{
	if (_currentState == PortOpened)
	{
		ClosePort();
	}

	_currentState = PortFailed;

	if (RS232_OpenComport(_COMPortNumber.c_str(),_baudrate,"8N1",&_COMPortHandle) == 0)
	{
	    _currentState = PortOpened ;
	}
}
示例#18
0
// 写数据
DWORD CMySerialPort::WriteData(unsigned char* sbuf, DWORD sendlen)
{
    DWORD dwBytesWritten = sendlen;
    DWORD dwErrorFlags;
    COMSTAT comStat;

    // 检查是否要关闭串口
    if (m_bClosePort)
    {
        ClosePort();
        return 0;
    }

    if (false == PeerIsValid())
    {
        LOG.err_log("请设置有效的目的串口!");
        return -1;
    }

    if (0 >= sendlen)
    {
        LOG.err_log("要发送的字节数必须大于0");
    }

    BOOL bWriteStat = FALSE; // 发送状态
    DWORD dwWritedLen = 0; // 实际发送的字节数
    DWORD dwTotalWrited = 0; // 累计已发送的字节总数

    while(dwBytesWritten > 0)
    {
        ClearCommError(m_peerHandle, &dwErrorFlags,&comStat);

        bWriteStat = WriteFile(m_peerHandle, sbuf + dwTotalWrited, dwBytesWritten,
            &dwWritedLen, NULL);

        if(!bWriteStat)
        {
            LOG.warn_log("写串口[%s]失败!", (LPCSTR)m_strComName);
            return sendlen - dwBytesWritten;
        }

        dwBytesWritten -= dwWritedLen;
        dwWritedLen += dwWritedLen;
    }
    //PurgeComm(m_portHandle, PURGE_TXABORT|
    //    PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR);
    return sendlen - dwBytesWritten;
}
示例#19
0
STDMETHODIMP CMicroFlash::Print(int iCopies)
{
	HRESULT r;
	char endLine [] = "\r\n";
	DWORD dwBytesWritten;
	char *pcPrintBuf;
	int iLineCount, n;

	// Assume failure
	r = S_FALSE;

	pcPrintBuf = NULL;
	iLineCount = 0;

	if(!OpenPort()) goto Exit;

	// Add formfeed to data
	m_strData.Append (TEXT("\x0C"));

	// Convert to char data
	n = m_strData.Length ();
	pcPrintBuf = new char [n + 1];
	wcstombs (pcPrintBuf, m_strData, n);
	pcPrintBuf [n] = 0;

	// Wakeup the printer
	for(iLineCount = 0; iLineCount < 10; iLineCount++)
		WriteFile(m_hComPort, endLine, strlen(endLine), &dwBytesWritten, NULL);

	Sleep(500);

	// Print the buffer
	for(iLineCount = 0; iLineCount < iCopies; iLineCount++)
		if(!WriteFile(m_hComPort, pcPrintBuf, strlen(pcPrintBuf), 
			&dwBytesWritten, NULL)) goto Exit;

	m_strData.Empty ();

	r = S_OK;

Exit:
	ClosePort ();
	delete [] pcPrintBuf;

	return r;
}
示例#20
0
// opens the serial port
// return code:
//   > 0 = fd for the port
//   -1 = open failed
int OpenPort(char* sPortNumber)
{
    char sPortName[64];
    printf("in OpenAdrPort port#=%s\n", sPortNumber);
    sprintf(sPortName, "/dev/ttyS%s", sPortNumber);
    printf("sPortName=%s\n", sPortName);

    // make sure port is closed
    ClosePort(fd);

    fd = open(sPortName, O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd < 0)
    {
        printf("open error %d %s\n", errno, strerror(errno));
    }
    else
    {
        struct termios my_termios;
        printf("fd is %d\n", fd);
        tcgetattr(fd, &my_termios);
        // NOTE: you may want to save the port attributes 
        //       here so that you can restore them later
        printf("old cflag=%08x\n", my_termios.c_cflag);
        printf("old oflag=%08x\n", my_termios.c_oflag);
        printf("old iflag=%08x\n", my_termios.c_iflag);
        printf("old lflag=%08x\n", my_termios.c_lflag);
        printf("old line=%02x\n", my_termios.c_line);

        tcflush(fd, TCIFLUSH);
        
        my_termios.c_cflag = B9600 | CS8 |CREAD | CLOCAL | HUPCL;
        
        cfsetospeed(&my_termios, B9600);
        tcsetattr(fd, TCSANOW, &my_termios);
 
        printf("new cflag=%08x\n", my_termios.c_cflag);
        printf("new oflag=%08x\n", my_termios.c_oflag);
        printf("new iflag=%08x\n", my_termios.c_iflag);
        printf("new lflag=%08x\n", my_termios.c_lflag);
        printf("new line=%02x\n", my_termios.c_line);
    } // end if
    return fd;
} // end OpenAdrPort
示例#21
0
//********************************************************************
BOOL CGatewayRS232ToWin32::OpenPort(CStdString strPortName, CErrorInfo* pErrorInfo)
{
    const int k_MaxPortNameSize = 20;
    const BOOL k_oChangeOnly = FALSE;

	if( !m_Rs232Hndl.OpenPort(strPortName) )
	{
		if(m_pErrorHandling) m_pErrorHandling->GetError(k_Error_I_OpeningPort, pErrorInfo);
        return FALSE;
	}

	//Configure default settings for port
    if(!SetPortSettings(m_dBaudrate, m_dTimeout, k_oChangeOnly, pErrorInfo))
    {
        ClosePort();
        return FALSE;
    }

    return TRUE;
}
示例#22
0
int InitPort(int port_num, int baudrate,
             int databits, int stopbits, int parity)
{
	int fd;

	fd = OpenPort(port_num);

	if(fd == -1) {
		return -1;
	}

	SetSpeed(fd, baudrate);

	if(SetParity(fd, databits, stopbits, parity) == FALSE) {
		DEBUG(DL_ERROR, "Set Parity Error!\n");
		ClosePort(fd);
		return -1;
	}

	return fd;
}
示例#23
0
int NcrComPort::OpenPort()
{
	if (hPort != 0)
		ClosePort();

    hPort = CreateFileA(
        this->Port,
        GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        0,
        NULL
    );

    if (!GetCommState(hPort, &dcb))
        return -1;

    FillDcb(dcb);

    if (!SetCommState(hPort, &dcb))
        return -1;
	return 0;
}
示例#24
0
CPSerialPort::~CPSerialPort()
{
	ClosePort();
}
示例#25
0
int main()
{
    // Initialize PortHandler Structs
    // Set the port path
    // Get methods and members of PortHandlerLinux or PortHandlerWindows
    int port_num = PortHandler(DEVICENAME);

    // Initialize PacketHandler Structs 
    PacketHandler();

    int dxl_comm_result = COMM_TX_FAIL;             // Communication result

    UINT8_T dxl_error = 0;                          // Dynamixel error
    UINT8_T dxl_baudnum_read;                       // Read baudnum

    // Open port
    if (OpenPort(port_num))
    {
        printf("Succeeded to open the port!\n");
    }
    else
    {
        printf("Failed to open the port!\n");
        printf("Press any key to terminate...\n");
        _getch();
        return 0;
    }

    // Set port baudrate
    if (SetBaudRate(port_num, BAUDRATE))
    {
        printf("Succeeded to change the baudrate!\n");
    }
    else
    {
        printf("Failed to change the baudrate!\n");
        printf("Press any key to terminate...\n");
        _getch();
        return 0;
    }

    // Read present baudrate of the controller
    printf("Now the controller baudrate is : %d\n", GetBaudRate(port_num));

    // Try factoryreset
    printf("[ID:%03d] Try factoryreset : ", DXL_ID);
    FactoryReset(port_num, PROTOCOL_VERSION, DXL_ID, OPERATION_MODE);
    if ((dxl_comm_result = GetLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
    {
        printf("Aborted\n");
        PrintTxRxResult(PROTOCOL_VERSION, dxl_comm_result);
        return 0;
    }
    else if ((dxl_error = GetLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
        PrintRxPacketError(PROTOCOL_VERSION, dxl_error);

    // Wait for reset
    printf("Wait for reset...\n");
    msecSleep(2000);

    printf("[ID:%03d] FactoryReset Success!\n", DXL_ID);

    // Set controller baudrate to Dynamixel default baudrate
    if (SetBaudRate(port_num, FACTORYRST_DEFAULTBAUDRATE))
    {
        printf("Succeed to change the controller baudrate to : %d\n", FACTORYRST_DEFAULTBAUDRATE);
    }
    else
    {
        printf("Failed to change the controller baudrate\n");
        printf("Press any key to terminate...\n");
        _getch();
        return 0;
    }

    // Read Dynamixel baudnum
    dxl_baudnum_read = Read1ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_BAUDRATE);
    if ((dxl_comm_result = GetLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
        PrintTxRxResult(PROTOCOL_VERSION, dxl_comm_result);
    else if ((dxl_error = GetLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
        PrintRxPacketError(PROTOCOL_VERSION, dxl_error);
    else
        printf("[ID:%03d] DXL baudnum is now : %d\n", DXL_ID, dxl_baudnum_read);

    // Write new baudnum
    Write1ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_BAUDRATE, NEW_BAUDNUM);
    if ((dxl_comm_result = GetLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
        PrintTxRxResult(PROTOCOL_VERSION, dxl_comm_result);
    else if ((dxl_error = GetLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
        PrintRxPacketError(PROTOCOL_VERSION, dxl_error);
    else
        printf("[ID:%03d] Set Dynamixel baudnum to : %d\n", DXL_ID, NEW_BAUDNUM);

    // Set port baudrate to BAUDRATE
    if (SetBaudRate(port_num, BAUDRATE))
    {
        printf("Succeed to change the controller baudrate to : %d\n", BAUDRATE);
    }
    else
    {
        printf("Failed to change the controller baudrate\n");
        printf("Press any key to terminate...\n");
        _getch();
        return 0;
    }

    msecSleep(200);

    // Read Dynamixel baudnum
    dxl_baudnum_read = Read1ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_BAUDRATE);
    if ((dxl_comm_result = GetLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
        PrintTxRxResult(PROTOCOL_VERSION, dxl_comm_result);
    else if ((dxl_error = GetLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
        PrintRxPacketError(PROTOCOL_VERSION, dxl_error);
    else
        printf("[ID:%03d] Dynamixel Baudnum is now : %d\n", DXL_ID, dxl_baudnum_read);

    // Close port
    ClosePort(port_num);

    return 0;
}
// 포트 sPortName을 dwBaud 속도로 연다.
// ThreadWatchComm 함수에서 포트에 무언가 읽혔을 때 MainWnd에 알리기
// 위해 WM_COMM_READ메시지를 보낼때 같이 보낼 wPortID값을 전달 받는다.
BOOL CCommThread::OpenPort(CString strPortName, 
					   DWORD dwBaud, BYTE byData, BYTE byStop, BYTE byParity )
{



	// Local 변수.
	COMMTIMEOUTS	timeouts;
	DCB				dcb;
	DWORD			dwThreadID;

	// overlapped structure 변수 초기화.
	m_osRead.Offset = 0;
	m_osRead.OffsetHigh = 0;
	//--> Read 이벤트 생성에 실패..
	if ( !(m_osRead.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL)) ) 	
	{
		return FALSE;
	}


	m_osWrite.Offset = 0;
	m_osWrite.OffsetHigh = 0;
	//--> Write 이벤트 생성에 실패..
	if (! (m_osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))
	{
		return FALSE;
	}

	//--> 포트명 저장..
	m_sPortName = strPortName;

	//--> 실제적인...RS 232 포트 열기..
	m_hComm = CreateFile( m_sPortName, 
						  GENERIC_READ | GENERIC_WRITE, 0, 0,
						  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 
						  NULL);


	//--> 포트 열기에 실해하면..
	if (m_hComm == (HANDLE) -1)
	{
		//AfxMessageBox("fail Port ofen");
		return FALSE;
	}
	

	//===== 포트 상태 설정. =====

	// EV_RXCHAR event 설정...데이터가 들어오면.. 수신 이벤트가 발생하게끔..
	SetCommMask( m_hComm, EV_RXCHAR);	

	// InQueue, OutQueue 크기 설정.
	SetupComm( m_hComm, BUFF_SIZE, BUFF_SIZE);	

	// 포트 비우기.
	PurgeComm( m_hComm,					
			   PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR);

	// timeout 설정.
	timeouts.ReadIntervalTimeout = 0xFFFFFFFF;
	timeouts.ReadTotalTimeoutMultiplier = 0;
	timeouts.ReadTotalTimeoutConstant = 0;
	timeouts.WriteTotalTimeoutMultiplier = 2*CBR_9600 / dwBaud;;
	timeouts.WriteTotalTimeoutConstant = 0;

	SetCommTimeouts( m_hComm, &timeouts);

	
	// dcb 설정.... 포트의 실제적인..제어를 담당하는 DCB 구조체값 셋팅..
	dcb.DCBlength = sizeof(DCB);

	//--> 현재 설정된 값 중에서..
	GetCommState( m_hComm, &dcb);	
	
	//--> 보드레이트를 바꾸고..
	dcb.BaudRate = dwBaud;
	
	//--> Data 8 Bit
	dcb.ByteSize = byData;

	//--> Noparity
	dcb.Parity = byParity;

	//--> 1 Stop Bit
	dcb.StopBits = byStop;




	//--> 포트를 재..설정값으로.. 설정해보고..
	if( !SetCommState( m_hComm, &dcb) )	
	{
		return FALSE;
	}
	
	//Sleep(60);

	// 포트 감시 쓰레드 생성.
	m_bConnected = TRUE;

	::SendMessage(hStartWnd, WM_COMM_OPEN, 1, 0);
	//--> 포트 감시 쓰레드 생성.
	m_hThreadWatchComm = CreateThread( NULL, 0, 
									   (LPTHREAD_START_ROUTINE)ThreadWatchComm, 
									   this, 0, &dwThreadID);

	//--> 쓰레드 생성에 실패하면..
	if (! m_hThreadWatchComm)
	{
		//--> 열린 포트를 닫고..
		ClosePort();
		return FALSE;
	}
	check = FALSE;
	

	return TRUE;
}
示例#27
0
// 포트 sPortName을 dwBaud 속도로 연다.
// ThreadWatchComm 함수에서 포트에 무언가 읽혔을 때 MainWnd에 알리기
// 위해 WM_COMM_READ메시지를 보낼때 같이 보낼 wPortID값을 전달 받는다.
BOOL CCommThread::OpenPort(char *sPortName, DWORD dwBaud, BYTE wPortID)
{
	// Local 변수.
	COMMTIMEOUTS	timeouts;
	DCB				dcb;
	DWORD			dwThreadID;

	// 변수 초기화
	m_bConnected = FALSE;
	m_wPortID	= wPortID; // COM1-> 0, COM2->1,,,,,

	// overlapped structure 변수 초기화.
	m_osRead.Offset = 0;
	m_osRead.OffsetHigh = 0;
	if (! (m_osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))	
		return FALSE;
	m_osWrite.Offset = 0;
	m_osWrite.OffsetHigh = 0;
	if (! (m_osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))
		return FALSE;
	
	// 포트 열기
//	m_sPortName = sPortName;
	m_hComm = CreateFile( LPCSTR(sPortName), // LPCSTR("COM4"), 
//	m_hComm = CreateFileA( LPCSTR("COM4"), 
		GENERIC_READ | GENERIC_WRITE, 0, NULL,
		OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 
		NULL);
	if (m_hComm == (HANDLE) -1) return FALSE;

	// 포트 상태 설정.

	// EV_RXCHAR event 설정
	SetCommMask( m_hComm, EV_RXCHAR);	

	// InQueue, OutQueue 크기 설정.
	SetupComm( m_hComm, 4096, 4096);	

	// 포트 비우기.
	PurgeComm( m_hComm,					
		PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR);

	// timeout 설정.
	timeouts.ReadIntervalTimeout = 0xFFFFFFFF;
	timeouts.ReadTotalTimeoutMultiplier = 0;
	timeouts.ReadTotalTimeoutConstant = 0;
	timeouts.WriteTotalTimeoutMultiplier = 2*CBR_9600 / dwBaud;
	timeouts.WriteTotalTimeoutConstant = 0;
	SetCommTimeouts( m_hComm, &timeouts);

	// dcb 설정
	dcb.DCBlength = sizeof(DCB);
	GetCommState( m_hComm, &dcb);	// 예전 값을 읽음.
	dcb.BaudRate = dwBaud;
	dcb.ByteSize = 8;
	dcb.Parity = 0;
	dcb.StopBits = 0;
	dcb.fInX = dcb.fOutX = 0;		// Xon, Xoff 사용안함.
	dcb.XonChar = ASCII_XON;
	dcb.XoffChar = ASCII_XOFF;
	dcb.XonLim = 100;
	dcb.XoffLim = 100;
	if (! SetCommState( m_hComm, &dcb))	return FALSE;

	// 포트 감시 쓰레드 생성.
	m_bConnected = TRUE;
	m_hThreadWatchComm = CreateThread( NULL, 0, 
		(LPTHREAD_START_ROUTINE)ThreadWatchComm, this, 0, &dwThreadID);
	if (! m_hThreadWatchComm)
	{
		ClosePort();
		return FALSE;
	}
    
	return TRUE;
}
示例#28
0
bool serialCOM::OpenPort(std::string portname)
{
	int confirm = -1;	// -1=error
	struct serial_struct new_serdrvinfo;	// new driver settings
	if (portisopen) return false;	// if port is already open => cancel and return "false"
	memset(&new_serdrvinfo, 0, sizeof(new_serdrvinfo));
	memset(&oldtio, 0, sizeof(oldtio));
	memset(&old_serdrvinfo, 0, sizeof(old_serdrvinfo));
	// OPEN PORT:
	fd = open(portname.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
	/* 		O_RDWR	 = read/write access;
	*		O_NOCTTY = ignore control characters
	*		O_NDELAY = ignore DCD-line		*/
	if (!(fd < 0))	// if port is now open
	{
		portisopen = true;
		currentportname = portname;
		confirm = ioctl(fd, TIOCEXCL, NULL);	// LOCK DEVICE
#ifdef __SERIALCOM_DEBUG__
		if (confirm == -1)
			std::cout << "serialCOM::OpenPort():   ioctl(..., TIOCEXCL, ...) failed with error " << errno << " " << strerror(errno) << "\n";
#endif
		confirm = fcntl(fd, F_SETFL, FNDELAY);	// function "read" shall return "0" if no data available
		if (confirm == -1)
		{
#ifdef __SERIALCOM_DEBUG__
			std::cout << "serialCOM::OpenPort():   fcntl(...) failed with error " << errno << "\n";
#endif
			confirm = ClosePort();
#ifdef __SERIALCOM_DEBUG__
			if (!confirm)
				std::cout << "serialCOM::OpenPort():   port couldn't be closed after error during opening process\n";
#endif
			return false;
		}
		// SAVE SETTINGS:
		confirm = ioctl(fd, TCGETS2, &oldtio);
		if (confirm == -1)
		{
#ifdef __SERIALCOM_DEBUG__
			std::cout << "serialCOM::OpenPort():   ioctl(..., TCGETS2, ...) failed with error " << errno << "\n";
#endif
			settingssaved = false;
		}
		else
			settingssaved = true;
		confirm = ioctl(fd, TIOCGSERIAL, &old_serdrvinfo);	// driver settings
		if (confirm != -1)
			ioctl_tiocgserial_supported = true;
		else
			ioctl_tiocgserial_supported = false;
		ioctl_tiocsserial_supported = false;
		flag_async_low_latency_supported = false;
		if (ioctl_tiocgserial_supported)
		{
			// CHANGE DRIVER SETTINGS:
			new_serdrvinfo = old_serdrvinfo;
			new_serdrvinfo.flags |= ASYNC_LOW_LATENCY;		// request low latency behaviour
			confirm = ioctl(fd, TIOCSSERIAL, &new_serdrvinfo);	// write driver settings
			/* NOTE: drivers should ignore ASYNC_LOW_LATENCY if they don't support it, but we don't rely on this behavior... */
			if (confirm != -1)
				flag_async_low_latency_supported = true;
			else
			{
				// Try again without the low latency flag
				new_serdrvinfo.flags &= ~ASYNC_LOW_LATENCY;
				confirm = ioctl(fd, TIOCSSERIAL, &new_serdrvinfo);
			}
			if (confirm != -1)
			{
				ioctl_tiocsserial_supported = true;
#ifdef __SERIALCOM_DEBUG__
				if (!(new_serdrvinfo.flags & ASYNC_LOW_LATENCY))
					std::cout << "serialCOM::OpenPort():   the driver doesn't support the ASYNC_LOW_LATENY flag\n";
#endif
			}
#ifdef __SERIALCOM_DEBUG__
			else
			{
				/* NOTE: some drivers (e.g. for many USB-serial devices) provide the TIOCGSERIAL ioctl, but no TIOCSSERIAL ioctl ! */
				std::cout << "serialCOM::OpenPort():   ioctl(..., TIOCSSERIAL, ...) failed with error " << errno << " " << strerror(errno) << "\n";
				std::cout << "serialCOM::OpenPort():   ioctl TIOCSSERIAL seems to be not supported\n";
			}
#endif
		}
/*
		// CLEAR BREAK (should not be necessary, because break is cancelled automatically after closing the device):
		confirm = ioctl(fd, TIOCCBRK, 0);    // break OFF
		if (confirm == -1)
			std::cout << "serialCOM::OpenPort():   ioctl(..., TIOCCBRK, ) failed with error " << errno << "\n";
		else
*/
		breakset = false;
		// CLEAR HARDWARE BUFFERS:
		confirm = ioctl(fd, TCFLSH, TCIOFLUSH);
		if (confirm == -1)
		{
#ifdef __SERIALCOM_DEBUG__
			std::cout << "serialCOM::OpenPort():   ioctl(..., TCFLSH, TCIOFLUSH) failed with error " << errno << " " << strerror(errno) << "\n";
#endif
			confirm = ClosePort();
#ifdef __SERIALCOM_DEBUG__
			if (!confirm)
				std::cout << "serialCOM::OpenPort():   port couldn't be closed after error during opening process\n";
#endif
			return false;
		}
		// CONFIGURE COMMUNICATION, SET STANDARD PORT-SETTINGS
		if (!SetPortSettings(9600, 8, 'N', 1 ))
		{
#ifdef __SERIALCOM_DEBUG__
			std::cout << "serialCOM::OpenPort():   Couldn't set standard port settings with SetPortSettings() !\n";
#endif
			confirm = ClosePort();
#ifdef __SERIALCOM_DEBUG__
			if (!confirm)
				std::cout << "serialCOM::OpenPort():   port couldn't be closed after error during opening process\n";
#endif
			return false;
			/* NOTE: SetPortSettings not only changes the 4 communication parameters.
			         It configures additional parameters (like control characters, timeouts, ...) which are
			         are important to ensure proper communication behavior !
			 */
		}
		// SET CONTROL LINES (DTR+RTS) TO STANDARD VALUES:
		confirm = SetControlLines(true, true);
#ifdef __SERIALCOM_DEBUG__
		if (!confirm)
			std::cout << "serialCOM::OpenPort():   Warning: couldn't set RTS+DTS control lines to standard values\n";
#endif
		/* NOTE: Call SetControlLines AFTER SetPortSettings, because drivers can
		 * change DTS+RTS when new baudrate/databits/parity/stopbits,
		 * especially at the first time after opening the port !		*/
		return true;
	}
	else
	{
#ifdef __SERIALCOM_DEBUG__
		std::cout << "serialCOM::OpenPort():   open(...) failed with error " << errno << " " << strerror(errno) << "\n";
#endif
		return false;
	}
}
示例#29
0
serialCOM::~serialCOM()
{
	if (portisopen) ClosePort();
}
示例#30
0
// Close and destroy a communication when we're done
CCPCBooster::~CCPCBooster()
{
	ClosePort();
}