HANDLE ControlUnit::OpenComPort(const char *name) { HANDLE handle = ::CreateFileA(name, GENERIC_READ|GENERIC_WRITE, 0/*exclusive access*/, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (handle != INVALID_HANDLE_VALUE) { SetupComm(handle, 2048, 2048); COMMTIMEOUTS com_time_outs; com_time_outs.ReadIntervalTimeout = 0xFFFFFFFF; com_time_outs.ReadTotalTimeoutMultiplier = 0; com_time_outs.ReadTotalTimeoutConstant = 1000; com_time_outs.WriteTotalTimeoutMultiplier = 0; com_time_outs.WriteTotalTimeoutConstant = 1000; if(!SetCommTimeouts(handle, &com_time_outs)) { ::CloseHandle(handle); return INVALID_HANDLE_VALUE; } DCB com_param; memset(&com_param, 0x00, sizeof(com_param)); if (!GetCommState(handle, &com_param)) { ::CloseHandle(handle); return INVALID_HANDLE_VALUE; } com_param.BaudRate = CBR_9600; com_param.ByteSize = 8; com_param.StopBits = ONESTOPBIT; com_param.Parity = NOPARITY; com_param.fAbortOnError = TRUE; com_param.fDtrControl = DTR_CONTROL_DISABLE; com_param.fRtsControl = RTS_CONTROL_DISABLE; com_param.fInX = FALSE; com_param.fOutX = FALSE; com_param.XonLim = 128; com_param.XoffLim = 128; com_param.fNull = FALSE; if (!SetCommState(handle, &com_param)) { ::CloseHandle(handle); return INVALID_HANDLE_VALUE; } ::PurgeComm(handle, PURGE_RXCLEAR|PURGE_TXABORT); ::CancelIo(handle); ::Sleep(2000); // Без этого не работает. Скорее всего что ардуина не увспевает сконфигурироваться. return handle; } return INVALID_HANDLE_VALUE; }
serial_t* serial_open(const char *device) { serial_t *h = calloc(sizeof(serial_t), 1); //COMMTIMEOUTS timeouts = {MAXDWORD, MAXDWORD, 3000, 0, 0}; // shorter timeout COMMTIMEOUTS timeouts = {MAXDWORD, MAXDWORD, 500, 0, 0}; /* Fix the device name if required */ char *devName; if (strlen(device) > 4 && device[0] != '\\') { devName = calloc(1, strlen(device) + 5); sprintf(devName, "\\\\.\\%s", device); } else { devName = device; } /* Create file handle for port */ h->fd = CreateFile(devName, GENERIC_READ | GENERIC_WRITE, 0, /* Exclusive access */ NULL, /* No security */ OPEN_EXISTING, 0, //FILE_FLAG_OVERLAPPED, NULL); if (devName != device) free(devName); if(h->fd == INVALID_HANDLE_VALUE) return NULL; SetupComm(h->fd, 4096, 4096); /* Set input and output buffer size */ SetCommTimeouts(h->fd, &timeouts); SetCommMask(h->fd, EV_ERR); /* Notify us of error events */ GetCommState(h->fd, &h->oldtio); /* Retrieve port parameters */ GetCommState(h->fd, &h->newtio); /* Retrieve port parameters */ PurgeComm(h->fd, PURGE_RXABORT | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_TXCLEAR); return h; }
BOOL openCom(int com_n,DWORD baudrate,HANDLE *hdlr) { #ifdef _DEBUG printf("[DEBUG] Connecting to COM%d at %d bauds : " ,com_n,(int)baudrate); #endif char com_name[16]; sprintf(com_name, "COM%d", com_n); *hdlr = CreateFile(com_name, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(*hdlr == INVALID_HANDLE_VALUE) { #ifdef _DEBUG printf("ERROR - invalid handle (COM%d)\r\n", com_n); #endif return FALSE; } // size of RX and TX buffers SetupComm(*hdlr, RX_SIZE, TX_SIZE); // com port config g_dcb.BaudRate=baudrate; if(!SetCommTimeouts(*hdlr, &g_cto) || !SetCommState(*hdlr, &g_dcb)) { #ifdef _DEBUG printf("ERROR - setting timeouts (COM%d)\r\n", com_n); #endif CloseHandle(*hdlr); return FALSE; } // empty the buffers PurgeComm(*hdlr, PURGE_TXCLEAR|PURGE_RXCLEAR|PURGE_TXABORT|PURGE_RXABORT); #ifdef _DEBUG printf("OK\r\n"); #endif return TRUE; }
// Open the serial port ser_handler ser_open( const char* sername ) { char portname[ WIN_MAX_PORT_NAME + 1 ]; HANDLE hComm; portname[ 0 ] = portname[ WIN_MAX_PORT_NAME ] = '\0'; _snprintf( portname, WIN_MAX_PORT_NAME, "\\\\.\\%s", sername ); hComm = CreateFile( portname, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0 ); if( hComm == INVALID_HANDLE_VALUE ) return WIN_ERROR; if( !SetupComm( hComm, 2048, 2048 ) ) return WIN_ERROR; if( !FlushFileBuffers( hComm ) || !PurgeComm( hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ) ) return WIN_ERROR; return hComm; }
bool StimThread::connectCOM(){ //Connect to serial port for stage hCom = CreateFile(comName.utf16(),GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0); //Zaber Stage Control if (hCom == INVALID_HANDLE_VALUE) { qDebug("Can't Connect to Stim"); return false; } //Configure Ports DCB cfg; GetCommState(hCom,&cfg); //cfg.BaudRate = 1200000; //cfg.BaudRate = 115200; //for magnus' board cfg.BaudRate = 460800; //Lakshmi's system //cfg.BaudRate = 230400; //Lakshmi's system cfg.ByteSize = 8; cfg.StopBits = ONESTOPBIT; cfg.Parity = NOPARITY; cfg.fDtrControl = DTR_CONTROL_DISABLE; cfg.fRtsControl = RTS_CONTROL_DISABLE; if(!SetCommState(hCom, &cfg )){ qDebug("Serial SetCommState Error %d - Stim ",GetLastError()); return false; } COMMTIMEOUTS timeouts; timeouts.ReadIntervalTimeout = 0; timeouts.ReadTotalTimeoutMultiplier = 100; timeouts.ReadTotalTimeoutConstant = 100; timeouts.WriteTotalTimeoutMultiplier = 100; timeouts.WriteTotalTimeoutConstant = 100; if (!SetCommTimeouts(hCom,&timeouts)) { qDebug("SetCommTimeouts Error 1 - Stim"); return false; } if (!SetupComm(hCom,2048,2048)){ qDebug("SetupComm Error 1 - Stim"); return false; } return true; };
static BOOL OpenConnection(LPCOMMINFO hCom, LPCTSTR lpPortName) { COMMTIMEOUTS CommTimeOuts; BOOL bRet; if (NULL == hCom) return (FALSE); // open communication resource hCom->hComPort = CreateFile(lpPortName, GENERIC_READ | GENERIC_WRITE, // access mode 0, // exclusive share NULL, // security attrs OPEN_EXISTING, 0, // 0 FILE_ATTRIBUTE_NORMAL NULL); if (hCom->hComPort == INVALID_HANDLE_VALUE) return (FALSE); // setup device buffers SetupComm(hCom->hComPort, 4096, 4096); // purge any information in the buffer PurgeComm(hCom->hComPort, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); // setup timeouts // CommTimeOuts.ReadIntervalTimeout = 10;//50; // CommTimeOuts.ReadTotalTimeoutMultiplier = 10;//5; // CommTimeOuts.ReadTotalTimeoutConstant = 200;//100; // CommTimeOuts.WriteTotalTimeoutMultiplier = 10;//5; // CommTimeOuts.WriteTotalTimeoutConstant = 50;//100; CommTimeOuts.ReadIntervalTimeout = 3;//50; CommTimeOuts.ReadTotalTimeoutMultiplier = 3;//5; CommTimeOuts.ReadTotalTimeoutConstant = 2;//100; CommTimeOuts.WriteTotalTimeoutMultiplier = 3;//5; CommTimeOuts.WriteTotalTimeoutConstant = 2;//100; bRet = SetCommTimeouts(hCom->hComPort, &CommTimeOuts); return (TRUE); } // end of OpenConnection()
static unsigned int port_buffers(struct rs232_port_t *p, unsigned int rb, unsigned int wb) { struct rs232_windows_t *wx = p->pt; DBG("p=%p p->pt=%p rb=%d wb=%d\n", (void *)p, p->pt, rb, wb); if (!rs232_port_open(p)) return RS232_ERR_PORT_CLOSED; if (!SetupComm(wx->fd, rb, wb)) { DBG("SetupComm() %s\n", last_error()); return RS232_ERR_UNKNOWN; } wx->r_buffer = rb; wx->w_buffer = wb; return RS232_ERR_NOERROR; }
// Open the rs232 port int rs232_open(char *_port, int baud_rate, int byte_size, int parity, int stop_bits) { // Make sure another port is not already opened ASSERT(!handle_com); // Open the existing COMX file to open the port handle_com = CreateFile( _port, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM, NULL); // Make sure it is opened if (handle_com == INVALID_HANDLE_VALUE) return 0; // buffer size for emission and reception SetupComm(handle_com, RS232_RX_SIZE, RS232_TX_SIZE); // COM port configuration g_dcb.BaudRate = baud_rate; g_dcb.ByteSize = byte_size; g_dcb.Parity = parity; g_dcb.StopBits = stop_bits; if(!SetCommTimeouts(handle_com, &g_cto) || !SetCommState(handle_com, &g_dcb)) { CloseHandle(handle_com); return 0; } // Flush buffers for emission and reception // DTR = 1 PurgeComm(handle_com, PURGE_TXCLEAR | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_RXABORT); EscapeCommFunction(handle_com, SETDTR); return 1; }
int serial_init(const char *port, unsigned long baud) { char fullPort[20]; sprintf(fullPort, "\\\\.\\%s", port); hSerial = CreateFile( fullPort, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hSerial == INVALID_HANDLE_VALUE) return FALSE; /* Set the baud rate. Always succeeds with mingw. */ if (!serial_baud(baud)) { serial_done(); return 0; } GetCommTimeouts(hSerial, &original_timeouts); timeouts = original_timeouts; timeouts.ReadIntervalTimeout = MAXDWORD; timeouts.ReadTotalTimeoutMultiplier = MAXDWORD; timeouts.WriteTotalTimeoutConstant = 1; timeouts.WriteTotalTimeoutMultiplier = 1; /* setup device buffers */ SetupComm(hSerial, 10000, 10000); /* purge any information in the buffer */ PurgeComm(hSerial, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); return TRUE; }
///////////////////////////////////////////////////////////////////////////////// // 函数:OpenPort // // 说明:打开指定的串口 // // 参数: // // pPort: 串口名称或设备路径,可用"COM1"或"\\.\COM1"两种方式,建议用后者 // // nBaudRate: 波特率 // // nParity: 奇偶校验 // // nByteSize: 数据字节宽度 // // nStopBits: 停止位 // // 返回值:打开的串口句柄 // ///////////////////////////////////////////////////////////////////////////////// HANDLE CSerialPort::OpenPort(const char* pPort, int nBaudRate, int nParity, int nByteSize, int nStopBits) { HANDLE hPort; DCB dcb; // 串口控制块 COMMTIMEOUTS timeouts = { // 串口超时控制参数 100, // 读字符间隔超时时间: 100 ms 1, // 读操作时每字符的时间: 1 ms (n个字符总共为n ms) 500, // 基本的(额外的)读超时时间: 500 ms 1, // 写操作时每字符的时间: 1 ms (n个字符总共为n ms) 100}; // 基本的(额外的)写超时时间: 100 ms hPort = CreateFile(pPort, // 串口名称或设备路径 GENERIC_READ | GENERIC_WRITE, // 读写方式 0, // 共享方式:独占 NULL, // 默认的安全描述符 OPEN_EXISTING, // 创建方式 0, // 不需设置文件属性 NULL); // 不需参照模板文件 if(hPort == INVALID_HANDLE_VALUE) { // printf("Open Port Failed\n"); return NULL; // 打开串口失败 } GetCommState(hPort, &dcb); // 取DCB dcb.BaudRate = nBaudRate; dcb.ByteSize = nByteSize; dcb.Parity = nParity; dcb.StopBits = nStopBits; SetCommState(hPort, &dcb); // 设置DCB SetupComm(hPort, 4096, 1024); // 设置输入输出缓冲区大小 SetCommTimeouts(hPort, &timeouts); // 设置超时 return hPort; }
int CComPrint::OpenCOM(int nCmdNum) { m_sComPort.Format(_T("COM%d"), nCmdNum); 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 (NULL != m_hCom) { m_bPortReady = SetupComm(m_hCom, 128, 128); m_bPortReady = GetCommState(m_hCom, &m_dcb); m_dcb.BaudRate = 9600; m_dcb.ByteSize = 8; m_dcb.Parity = NOPARITY; m_dcb.StopBits = ONESTOPBIT; m_dcb.fAbortOnError = TRUE; m_dcb.fBinary = TRUE; m_bPortReady = SetCommState(m_hCom, &m_dcb); 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); return 0; } return -1; }
int ConnPort::OpenPort(TCHAR *szPort,int iBaudrate,int iParity,int iDataBits,int iStopBits) { DWORD dwThreadID=0; g_iExitFlag=0; m_hPort=NULL; m_hPort=CreateFile(szPort, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if(!m_hPort) { m_hPort=NULL; wprintf(TEXT("open port failed!!!\r\n")); return FALSE; } //指定端口检测的事件集 SetCommMask(m_hPort,EV_RXCHAR); //设置缓冲区,内部输入、输出缓冲区大小 SetupComm(m_hPort,1024,1024); //刷新缓冲区信息->输入、输出缓冲区 PurgeComm(m_hPort,PURGE_TXCLEAR|PURGE_RXCLEAR); if(!ConfigPort(iBaudrate,iParity,iDataBits,iStopBits)) return FALSE; if(!CommTimeouts())return FALSE; //创建读写线程 m_hThreadRead = CreateThread(0,0,(LPTHREAD_START_ROUTINE)ReadThreadProc, (void*)this,0,&dwThreadID); m_hThreadWrite = CreateThread(0,0,(LPTHREAD_START_ROUTINE)WriteThreadProc, (void*)this,0,&dwThreadID); m_hDataParse = CreateThread(0,0,(LPTHREAD_START_ROUTINE)PareDataProc, (void*)this,0,&dwThreadID); m_bIsConnect=TRUE; return TRUE; }
void serial_init() { DCB dcbSerialParams = {0}; hSerial = CreateFile("COM6",GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); if(hSerial==INVALID_HANDLE_VALUE) { //some other error occurred. Inform user. printf("Open COM port fail.\n"); if(GetLastError()==ERROR_FILE_NOT_FOUND) { //serial port does not exist. Inform user. printf("COM port not found.\n"); } } dcbSerialParams.DCBlength=sizeof(dcbSerialParams); if (!GetCommState(hSerial, &dcbSerialParams)) { //error getting state printf("GetCommState Error\n"); } dcbSerialParams.BaudRate=CBR_115200; dcbSerialParams.ByteSize=8; dcbSerialParams.StopBits=ONESTOPBIT; dcbSerialParams.Parity=NOPARITY; if(!SetCommState(hSerial, &dcbSerialParams)) { printf("SetCommState Error\n"); } if (!SetupComm(hSerial,2048,2048)) { printf("Set Buffer size Error\n"); } //SetupComm(hSerial, 1024, 1024); }
bool SerialPort::config(int baudRate, int byteSize) { if(!SetupComm(hCom, 1024, 1024)) return false; DCB dcbConfig; if(GetCommState(hCom, &dcbConfig)) { /* Configuring Serial Port Settings */ dcbConfig.BaudRate = baudRate; dcbConfig.ByteSize = byteSize; dcbConfig.Parity = NOPARITY; dcbConfig.StopBits = ONESTOPBIT; dcbConfig.fBinary = TRUE; dcbConfig.fParity = FALSE; } else return false; if(!SetCommState(hCom, &dcbConfig)) return false; COMMTIMEOUTS commTimeout; if(GetCommTimeouts(hCom, &commTimeout)) { /* Configuring Read & Write Time Outs */ commTimeout.ReadIntervalTimeout = 1000; //One second commTimeout.ReadTotalTimeoutConstant = 1000; //One second commTimeout.ReadTotalTimeoutMultiplier = 0; commTimeout.WriteTotalTimeoutConstant = 1000; //One second commTimeout.WriteTotalTimeoutMultiplier = 0; } else return false; if(SetCommTimeouts(hCom, &commTimeout)) return true; else return false; }
BOOL CSerial::Init(DWORD dwBaudRate) { DCB dcb; if(!GetCommState(m_hDev, &dcb)) { //RETAILMSG(DBGMSG, (L"Serial::Init() error GetCommState()\r\n") ); return FALSE; } dcb.DCBlength = sizeof(dcb); dcb.BaudRate = dwBaudRate; dcb.fParity = FALSE; dcb.fNull = FALSE; dcb.StopBits = ONESTOPBIT; dcb.Parity = NOPARITY; dcb.ByteSize = 8; // dcb.EvtChar = '@'; //×¢²áÒ»¸öʼþ×Ö·û if(!SetCommState(m_hDev, &dcb)) { //RETAILMSG(DBGMSG, (L"Serial::Init() error SetCommState()\r\n") ); return FALSE; } if(!SetupComm(m_hDev, 4096, 4096)) { //RETAILMSG(DBGMSG, (L"Serial::Init() error SetupComm()\r\n") ); return FALSE; } SetReadTimeout(100,100); return TRUE; }
bool Comm::ConnectComm( const CString& comName ) { HANDLE hCom; hCom=CreateFile(comName, GENERIC_READ|GENERIC_WRITE, //允许读和写 0, //独占方式 NULL, OPEN_EXISTING, //打开而不是创建 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, //重叠方式 NULL); if( hCom== INVALID_HANDLE_VALUE) return false; SetupComm(hCom,100,100); //输入缓冲区和输出缓冲区的大小都是100 COMMTIMEOUTS TimeOuts; //设定读超时 TimeOuts.ReadIntervalTimeout=MAXDWORD; TimeOuts.ReadTotalTimeoutMultiplier=50; TimeOuts.ReadTotalTimeoutConstant=100; //设定写超时 TimeOuts.WriteTotalTimeoutMultiplier=100; TimeOuts.WriteTotalTimeoutConstant=500; SetCommTimeouts(hCom,&TimeOuts); //设置超时 DCB dcb; GetCommState(hCom,&dcb); dcb.BaudRate=9600; //波特率为9600 dcb.ByteSize=8; //每个字节有8位 dcb.Parity=NOPARITY; //无奇偶校验位 dcb.StopBits=ONESTOPBIT; //1个停止位 SetCommState(hCom,&dcb); PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); itsCommAndWnd.hCom = hCom; return true; }
BOOL SetBufAndTimeOut(HANDLE Hcom) { /*���ô���*/ //����I/O������(����ͨ�����ʵ���) if (SetupComm(Hcom,//�豸���� 1024,//���뻺������С(�ֽ�) 1024 //������������С(�ֽ�) ) == FALSE) { Err = Err_SetBuffer; return FALSE; } //�������ó�ʱ�Ľṹ�� ע:��ʱ���������������õij�ʱʱ����δ���ɶ�/д����,��/д�����Ի����� COMMTIMEOUTS TimeOuts; /* 1.��/д�ܳ�ʱ=ϵ��*�ַ���+���� 2.ϵ���볣����Ϊ0����ʾ��ʹ�øó�ʱ 3.����������ʱΪMAXDWORD�Ҷ�ϵ���ͳ�����Ϊ0,��ô�������ͻ���������,�����Ƿ�����Ҫ�����ַ� 4.�첽ͨ��ʱ,��/д���ܻ������ɲ���ǰ����,��ʱ��ʱ�涨���Dz���������ʱ�� 5.ʱ�䵥λ��Ϊms */ //�趨����ʱ TimeOuts.ReadIntervalTimeout = MAXDWORD;//��������ʱ TimeOuts.ReadTotalTimeoutMultiplier = 0;//��ʱ��ϵ�� TimeOuts.ReadTotalTimeoutConstant = 1;//��ʱ�䳣�� //�趨д��ʱ TimeOuts.WriteTotalTimeoutMultiplier = 50;//дʱ��ϵ�� TimeOuts.WriteTotalTimeoutConstant = 1000;//дʱ�䳣�� //д�볬ʱ����,��ȡ��ǰ��ʱ����ʹ��GetCommTimeouts() if (SetCommTimeouts(Hcom, &TimeOuts) == FALSE) { Err = Err_SetTimeOuts; return FALSE; } return TRUE; }
/* Win32 serial communication with the Target */ QSpyStatus PAL_openTargetSer(char const *comName, int baudRate) { DCB dcb; char comPortName[40]; char comSettings[120]; /* setup the PAL virtual table for the Serial communication... */ PAL_vtbl.getEvt = &ser_getEvt; PAL_vtbl.send2Target = &ser_send2Target; PAL_vtbl.cleanup = &ser_cleanup; /* open serial port (use \\.\COM<num> name to allow large <num>)... */ SNPRINTF_S(comPortName, sizeof(comPortName), "\\\\.\\%s", comName); l_serHNDL = CreateFile(comPortName, GENERIC_READ | GENERIC_WRITE, 0U, /* exclusive access */ NULL, /* no security attrs */ OPEN_EXISTING, 0U, /* standard (not-overlapped) I/O */ NULL); if (l_serHNDL == INVALID_HANDLE_VALUE) { fprintf(stderr, "*** PAL: Error by opening COM port: %s at %d\n", comName, baudRate); return QSPY_ERROR; } /* configure the serial port... */ SNPRINTF_S(comSettings, sizeof(comSettings), "baud=%d parity=N data=8 stop=1 odsr=off dtr=on octs=off rts=on", baudRate); dcb.DCBlength = sizeof(DCB); if (!GetCommState(l_serHNDL, &dcb)) { fprintf(stderr, "*** PAL: Error retreiving COM port settings\n"); return QSPY_ERROR; } /* dill in the DCB... */ dcb.fAbortOnError = 0U; /* don't abort on error */ if (!BuildCommDCB(comSettings, &dcb)) { fprintf(stderr, "*** PAL: Error parsing COM port settings\n"); return QSPY_ERROR; } if (!SetCommState(l_serHNDL, &dcb)) { fprintf(stderr, "*** PAL: Error setting up the COM port\n"); return QSPY_ERROR; } /* setup the serial port buffers... */ SetupComm(l_serHNDL, 4*1024, /* 4K input buffer */ 4*1024); /* 4K output buffer */ /* purge any information in the buffers */ PurgeComm(l_serHNDL, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); /* the read timeouts for the serial communication are set accorging * to the following remark from the Win32 help documentation: * * If an application sets ReadIntervalTimeout and * ReadTotalTimeoutMultiplier to MAXDWORD and sets * ReadTotalTimeoutConstant to a value greater than zero and less than * MAXDWORD, one of the following occurs when the ReadFile function * is called: * 1. If there are any characters in the input buffer, ReadFile * returns immediately with the characters in the buffer. * 2. If there are no characters in the input buffer, ReadFile waits * until a character arrives and then returns immediately. * 3. If no character arrives within the time specified by * ReadTotalTimeoutConstant, ReadFile times out. */ l_timeouts.ReadIntervalTimeout = MAXDWORD; l_timeouts.ReadTotalTimeoutMultiplier = MAXDWORD; l_timeouts.ReadTotalTimeoutConstant = PAL_TOUT_MS; /* the write timeouts for the serial communication are set accorging * to the following remark from the Win32 help documentation: * * A value of zero for both the WriteTotalTimeoutMultiplier and * WriteTotalTimeoutConstant members indicates that total time-outs * are not used for write operations. * * This means that the WriteFile() returns immediately and the * serial driver must cache any bytes that have not been sent yet. * (see also the output buffer setting for SetupComm() earlier). * * Exceeding the write buffer capacity indicates that the Target * cannot accept all the bytes at this rate. This error will produce * an error message to the screen. */ l_timeouts.WriteTotalTimeoutMultiplier = 0; l_timeouts.WriteTotalTimeoutConstant = 0; SetCommTimeouts(l_serHNDL, &l_timeouts); return QSPY_SUCCESS; }
//--------------------------------------------------------------------------- // Attempt to open a com port. Keep the handle in ComID. // Set the starting baud rate to 115200. // // 'portnum' - number 0 to MAX_PORTNUM-1. This number provided will // be used to indicate the port number desired when calling // all other functions in this library. // // 'port_zstr' - zero terminate port name. For this platform // use format COMX where X is the port number. // // // Returns: TRUE(1) - success, COM port opened // FALSE(0) - failure, could not open specified port // bool OpenCOM(int portnum, char *port_zstr) { char tempstr[80]; short fRetVal; COMMTIMEOUTS CommTimeOuts; DCB dcb; // open COM device if ((ComID[portnum] = CreateFile( port_zstr, GENERIC_READ | GENERIC_WRITE, 0, NULL, // no security attrs OPEN_EXISTING, FILE_FLAG_OVERLAPPED, // overlapped I/O NULL )) == (HANDLE) -1 ) { ComID[portnum] = 0; return (FALSE) ; } else { // create events for detection of reading and write to com port osRead[portnum].hEvent = CreateEvent(NULL,TRUE,FALSE,tempstr); osWrite[portnum].hEvent = CreateEvent(NULL,TRUE,FALSE,tempstr); // get any early notifications SetCommMask(ComID[portnum], EV_RXCHAR | EV_TXEMPTY | EV_ERR | EV_BREAK); // setup device buffers SetupComm(ComID[portnum], 2048, 2048); // purge any information in the buffer PurgeComm(ComID[portnum], PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ); // set up for overlapped non-blocking I/O CommTimeOuts.ReadIntervalTimeout = 0; CommTimeOuts.ReadTotalTimeoutMultiplier = 20; CommTimeOuts.ReadTotalTimeoutConstant = 40; CommTimeOuts.WriteTotalTimeoutMultiplier = 20; CommTimeOuts.WriteTotalTimeoutConstant = 40; SetCommTimeouts(ComID[portnum], &CommTimeOuts); // setup the com port GetCommState(ComID[portnum], &dcb); dcb.BaudRate = CBR_115200; // current baud rate dcb.fBinary = TRUE; // binary mode, no EOF check dcb.fParity = FALSE; // enable parity checking dcb.fOutxCtsFlow = FALSE; // CTS output flow control dcb.fOutxDsrFlow = FALSE; // DSR output flow control dcb.fDtrControl = DTR_CONTROL_ENABLE; // DTR flow control type dcb.fDsrSensitivity = FALSE; // DSR sensitivity dcb.fTXContinueOnXoff = TRUE; // XOFF continues Tx dcb.fOutX = FALSE; // XON/XOFF out flow control dcb.fInX = FALSE; // XON/XOFF in flow control dcb.fErrorChar = FALSE; // enable error replacement dcb.fNull = FALSE; // enable null stripping dcb.fRtsControl = RTS_CONTROL_ENABLE; // RTS flow control dcb.fAbortOnError = FALSE; // abort reads/writes on error dcb.XonLim = 0; // transmit XON threshold dcb.XoffLim = 0; // transmit XOFF threshold dcb.ByteSize = 8; // number of bits/byte, 4-8 dcb.Parity = NOPARITY; // 0-4=no,odd,even,mark,space dcb.StopBits = ONESTOPBIT; // 0,1,2 = 1, 1.5, 2 dcb.XonChar = 0; // Tx and Rx XON character dcb.XoffChar = 1; // Tx and Rx XOFF character dcb.ErrorChar = 0; // error replacement character dcb.EofChar = 0; // end of input character dcb.EvtChar = 0; // received event character fRetVal = SetCommState(ComID[portnum], &dcb); } // check if successfull if (!fRetVal) { CloseHandle(ComID[portnum]); ComID[portnum] = 0; return false; } return true; }
/************************************************************************** * -Routine: setup_dcb ( GIZ_PORT, short, short ) * * -Description: Setups the Device Control Block * * -Arguments: None * * -Notes: * * -Returns : gizzmo error code for the windows' comm error passed in. * *************************************************************************/ static long setup_dcb ( GIZ_PORT port, short settings, short lineflag ) { DWORD commerr; BOOL err; // append the decimal comm port number to the string "COMx" if ((port >= 0) && (port <= 8)) { comPortString[3] = (char)(port+1 + 0x30); comPortString[4] = 0x00; } PortID = CreateFile(comPortString, GENERIC_READ|GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); if(PortID == INVALID_HANDLE_VALUE) return ((long)INVALID_HANDLE_VALUE); GetCommState(PortID,&CommDCB); // Get the current system default // Setup DCB CommDCB.DCBlength = sizeof(DCB); CommDCB.BaudRate = CBR_9600; // current baud rate CommDCB.fBinary = TRUE; // binary mode, no EOF check CommDCB.fParity =FALSE; // enable parity checking CommDCB.fOutxCtsFlow = FALSE; // CTS output flow control CommDCB.fOutxDsrFlow = FALSE; // DSR output flow control if (lineflag == LINES_HIGH) { CommDCB.fDtrControl= DTR_CONTROL_ENABLE; // DTR flow control type CommDCB.fRtsControl= RTS_CONTROL_ENABLE; // RTS flow control } else { CommDCB.fDtrControl= DTR_CONTROL_DISABLE; // DTR flow control type CommDCB.fRtsControl= RTS_CONTROL_DISABLE; // RTS flow control } CommDCB.fDsrSensitivity = FALSE; // DSR sensitivity CommDCB.fTXContinueOnXoff= FALSE; // XOFF continues Tx CommDCB.fOutX= FALSE; // XON/XOFF out flow control CommDCB.fInX= FALSE; // XON/XOFF in flow control CommDCB.fErrorChar= FALSE; // enable error replacement CommDCB.fNull= FALSE; // enable null stripping CommDCB.fAbortOnError= FALSE; // abort reads/writes on error //CommDCB.fDummy2:17; // reserved // wReserved; // not currently used CommDCB.XonLim; // transmit XON threshold CommDCB.XoffLim; // transmit XOFF threshold CommDCB.ByteSize = 8; // number of bits/byte, 4-8 CommDCB.Parity = NOPARITY; // 0-4=no,odd,even,mark,space CommDCB.StopBits = 0; // 0,1,2 = 1, 1.5, 2 SetCommState(PortID,&CommDCB); err = SetupComm( PortID, INQUE_SIZE, OUTQUE_SIZE ); if(err==FALSE) { commerr = GetLastError(); return (commerr); } else return(0); //return 0 if ok; }
int OCP_DataStreamInput_Thread::OpenComPortPhysical(const wxString &com_name, int baud_rate) { // Set up the serial port wxString xcom_name = com_name; xcom_name.Prepend(_T("\\\\.\\")); // Required for access to Serial Ports greater than COM9 #ifdef SERIAL_OVERLAPPED DWORD open_flags = FILE_FLAG_OVERLAPPED; #else DWORD open_flags = 0; #endif HANDLE hSerialComm = CreateFile(xcom_name.fn_str(), // Port Name GENERIC_READ | GENERIC_WRITE, // Desired Access 0, // Shared Mode NULL, // Security OPEN_EXISTING, // Creation Disposition open_flags, NULL); if(hSerialComm == INVALID_HANDLE_VALUE) { // ThreadMessage(_T("Error:Invalid Handle")); return (0 - abs((int)::GetLastError())); } DWORD err; COMSTAT cs; ClearCommError(hSerialComm, &err, &cs); if(!SetupComm(hSerialComm, 1024, 1024)) { // ThreadMessage(_T("Error:SetupComm")); if(hSerialComm != INVALID_HANDLE_VALUE) CloseHandle( hSerialComm ); return (0 - abs((int)::GetLastError())); } DCB dcbConfig; if(GetCommState(hSerialComm, &dcbConfig)) // Configuring Serial Port Settings { dcbConfig.BaudRate = baud_rate; dcbConfig.ByteSize = 8; dcbConfig.Parity = NOPARITY; dcbConfig.StopBits = ONESTOPBIT; dcbConfig.fBinary = TRUE; dcbConfig.fRtsControl = RTS_CONTROL_ENABLE; dcbConfig.fDtrControl = DTR_CONTROL_ENABLE; dcbConfig.fOutxDsrFlow = false; dcbConfig.fOutxCtsFlow = false; dcbConfig.fDsrSensitivity = false; dcbConfig.fOutX = false; dcbConfig.fInX = false; dcbConfig.fInX = false; dcbConfig.fInX = false; } else { // ThreadMessage(_T("Error:GetCommState")); if(hSerialComm != INVALID_HANDLE_VALUE) CloseHandle( hSerialComm ); return (0 - abs((int)::GetLastError())); } if(!SetCommState(hSerialComm, &dcbConfig)) { // ThreadMessage(_T("Error:SetCommState")); if(hSerialComm != INVALID_HANDLE_VALUE) CloseHandle( hSerialComm ); return (0 - abs((int)::GetLastError())); } COMMTIMEOUTS commTimeout; int TimeOutInSec = 2; commTimeout.ReadIntervalTimeout = 1000*TimeOutInSec; commTimeout.ReadTotalTimeoutConstant = 1000*TimeOutInSec; commTimeout.ReadTotalTimeoutMultiplier = 0; commTimeout.WriteTotalTimeoutConstant = 1000*TimeOutInSec; commTimeout.WriteTotalTimeoutMultiplier = 0; if(!SetCommTimeouts(hSerialComm, &commTimeout)) { // ThreadMessage(_T("Error:SetCommTimeouts")); if(hSerialComm != INVALID_HANDLE_VALUE) CloseHandle( hSerialComm ); return (0 - abs((int)::GetLastError())); } return (int)hSerialComm; }
BOOL ARRAY3600OBJ::SetupComPort(int port) { connected=FALSE; int sav_port; DCB dcb = {0}; char PORTNAME[10]; sav_port=comport; BreakDownComPort(); comport= port ; // set tty structure for the specified port if (!port) goto failed; sprintf(PORTNAME,"\\\\.\\COM%d",port); comdev = CreateFile( PORTNAME,GENERIC_READ | GENERIC_WRITE, 0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); if (comdev == INVALID_HANDLE_VALUE) goto failed; if (!GetCommState(comdev, &dcb)) // get current DCB settings { report_error("GetCommState");goto failed; } // update DCB rate, byte size, parity, and stop bits size dcb.DCBlength = sizeof(dcb); dcb.BaudRate = baudrate; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; dcb.EvtChar = '\0'; // update flow control settings dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fRtsControl = RTS_CONTROL_ENABLE; dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fDsrSensitivity = FALSE;; dcb.fOutX = FALSE; dcb.fInX = FALSE; dcb.fTXContinueOnXoff = FALSE; dcb.XonChar = 0; dcb.XoffChar = 0; dcb.XonLim = 0; dcb.XoffLim = 0; dcb.fParity = FALSE; //TRUE; if (!SetCommState(comdev, &dcb)) // set new state { report_error("SetCommState failed"); goto failed;} if (!SetupComm(comdev, 1024, 1024)) // set comm buffer sizes { report_error("SetupComm failed");goto failed;} if (!EscapeCommFunction(comdev, SETDTR)) // raise DTR { report_error("EscapeCommFunction failed");goto failed;} SetCommMask (comdev, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING); return(TRUE); failed: { char sztemp[100]; sprintf(sztemp, "The Port COM%d is not available. Please select another Com-Port.",port); write_logfile("COMPORT %d open failed.",port); report_error(sztemp); comport=sav_port; comdev=INVALID_HANDLE_VALUE; connected=FALSE; return FALSE; } }
// 포트 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; }
/*----------------------------------------------------------------------------- FUNCTION: SetupCommPort( int Port ) PURPOSE: Setup Communication Port with our settings -----------------------------------------------------------------------------*/ BOOL SetupCommPort(int port) { DWORD dwReadStatId; DWORD dwWriteStatId; int sav_port,sav_pause; DCB dcb = {0}; char PORTNAME[10]; if (!port) return(false); sav_port=TTY.PORT; sav_pause=TTY.read_pause; TTY.read_pause=1; BreakDownCommPort(); TTY.PORT = port ; // set tty structure for the specified port sprintf(PORTNAME,"\\\\.\\COM%d",port); PACKET.readstate=0; PACKET.number=0; PACKET.old_number=0; PACKET.info=0; // open communication port handle // TTY.COMDEV = CreateFile( PORTNAME,GENERIC_READ | GENERIC_WRITE, // 0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,0); TTY.COMDEV = CreateFile( PORTNAME,GENERIC_READ | GENERIC_WRITE, 0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); if (TTY.COMDEV == INVALID_HANDLE_VALUE) goto failed; if (!GetCommState(TTY.COMDEV, &dcb)) // get current DCB settings { report_error("GetCommState");goto failed; } // update DCB rate, byte size, parity, and stop bits size dcb.DCBlength = sizeof(dcb); dcb.BaudRate = TTY.BAUDRATE; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; dcb.EvtChar = '\0'; // update flow control settings dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fRtsControl = RTS_CONTROL_ENABLE; if (TTY.FLOW_CONTROL) { dcb.fOutxCtsFlow = TRUE; dcb.fOutxDsrFlow = TRUE; } else { dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; } dcb.fDsrSensitivity = FALSE;; dcb.fOutX = FALSE; dcb.fInX = FALSE; dcb.fTXContinueOnXoff = FALSE; dcb.XonChar = 0; dcb.XoffChar = 0; dcb.XonLim = 0; dcb.XoffLim = 0; dcb.fParity = FALSE; //TRUE; if (!SetCommState(TTY.COMDEV, &dcb)) // set new state { report_error("SetCommState failed"); goto failed;} // set comm buffer sizes if (!SetupComm(TTY.COMDEV, 1024, 1024)) { report_error("SetupComm failed");goto failed;} if (!EscapeCommFunction(TTY.COMDEV, SETDTR)) // raise DTR { report_error("EscapeCommFunction failed");goto failed;} SetCommMask (TTY.COMDEV, EV_RXCHAR | EV_CTS | EV_DSR | EV_RLSD | EV_RING); // start the reader and writer threads fThreadDone = FALSE; TTY.READERTHREAD = CreateThread( NULL, 1000, (LPTHREAD_START_ROUTINE) ReaderProc, 0, 0, &dwReadStatId); if (TTY.READERTHREAD == NULL) { report_error("CreateThread failed"); goto failed;} TTY.WRITERTHREAD = CreateThread( NULL, 1000, (LPTHREAD_START_ROUTINE) WriterProc, 0, 0, &dwWriteStatId); if (TTY.WRITERTHREAD == NULL) { report_error("CreateWriterThread failed"); goto failed;} write_logfile("COMPORT opened: %s", PORTNAME); TTY.amount_to_write=0; TTY.read_pause=sav_pause; return TRUE; failed: { char sztemp[100]; write_logfile("COMPORT open failed"); sprintf(sztemp, "The Port COM%d is not available. Please select another Com-Port.",TTY.PORT); report_error(sztemp); TTY.read_pause=sav_pause; TTY.PORT=sav_port; TTY.COMDEV=INVALID_HANDLE_VALUE; TTY.CONNECTED=FALSE; TTY.amount_to_write=0; return FALSE; } }
bool InitCom(HANDLE& m_hCom, OVERLAPPED& wrOverlapped, char* comNum) { //第一步,打开串口 //HANDLE m_hCom; m_hCom = CreateFile((LPCWSTR)comNum, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (m_hCom == INVALID_HANDLE_VALUE) { std::cout << "CreateFile fail!" << endl; return false; } //cout << "CreateFile OK!" << endl; //第二步,设置缓冲区大小 if (!SetupComm(m_hCom, 2048, 2048)) { cout << "SetupComm fail! Close Comm!" << endl; CloseHandle(m_hCom); return false; } //cout << "SetupComm OK!" << endl; //第三步,设置超时 COMMTIMEOUTS TimeOuts; memset(&TimeOuts, 0, sizeof(TimeOuts)); TimeOuts.ReadIntervalTimeout = MAXDWORD; TimeOuts.ReadTotalTimeoutConstant = 0; TimeOuts.ReadTotalTimeoutMultiplier = 0; TimeOuts.WriteTotalTimeoutConstant = 2000; TimeOuts.WriteTotalTimeoutMultiplier = 2000; SetCommTimeouts(m_hCom, &TimeOuts); //第四步,设置串口参数 DCB dcb; if (!GetCommState(m_hCom, &dcb)) { cout << "GetCommState fail! Comm close" << endl; CloseHandle(m_hCom); return false; } //cout << "GetCommState OK!" << endl; dcb.DCBlength = sizeof(dcb); if (!BuildCommDCB((WCHAR*)_T("9600,n,8,1"), &dcb))//填充DCB的数据传输率、奇偶校验类型、数据位、停止位 { //参数修改错误,进行错误处理 cout << "BuileCOmmDCB fail,Comm close!" << endl; CloseHandle(m_hCom); return false; } if (SetCommState(m_hCom, &dcb)) { //cout << "SetCommState OK!" << endl; } //第五步,建立并初始化重叠结构 ZeroMemory(&wrOverlapped, sizeof(wrOverlapped)); if (wrOverlapped.hEvent != NULL) { ResetEvent(wrOverlapped.hEvent); wrOverlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); } return true; }
int xbee_ser_open( xbee_serial_t *serial, uint32_t baudrate) { char buffer[sizeof("\\\\.\\COM9999")]; HANDLE hCom; COMMTIMEOUTS timeouts; int err; if (serial == NULL || serial->comport > 9999) { #ifdef XBEE_SERIAL_VERBOSE printf( "%s: -EINVAL (serial=%p)\n", __FUNCTION__, serial); #endif return -EINVAL; } // if XBee's existing hCom handle is not null, need to close it // (unless we're just changing the baud rate?) // Assume serial port has not changed if port is already open, and skip the // CreateFile step. if (serial->hCom) { // serial port is already open hCom = serial->hCom; serial->hCom = NULL; #ifdef XBEE_SERIAL_VERBOSE printf( "%s: port already open (hCom=%p)\n", __FUNCTION__, hCom); #endif } else { snprintf( buffer, sizeof buffer, "\\\\.\\COM%u", serial->comport); hCom = CreateFile( buffer, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hCom == INVALID_HANDLE_VALUE) { #ifdef XBEE_SERIAL_VERBOSE printf( "%s: error %lu opening handle to %s\n", __FUNCTION__, GetLastError(), buffer); #endif return -EIO; } } // set up a transmit and receive buffers SetupComm( hCom, XBEE_SER_RX_BUFSIZE, XBEE_SER_TX_BUFSIZE); /* Set the COMMTIMEOUTS structure. Per MSDN documentation for ReadIntervalTimeout, "A value of MAXDWORD, combined with zero values for both the ReadTotalTimeoutConstant and ReadTotalTimeoutMultiplier members, specifies that the read operation is to return immediately with the bytes that have already been received, even if no bytes have been received." */ if (!GetCommTimeouts( hCom, &timeouts)) { #ifdef XBEE_SERIAL_VERBOSE printf( "%s: %s failed (%lu initializing COM%u)\n", __FUNCTION__, "GetCommTimeouts", GetLastError(), serial->comport); #endif CloseHandle( hCom); return -EIO; } timeouts.ReadIntervalTimeout = MAXDWORD; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = 0; if (!SetCommTimeouts( hCom, &timeouts)) { #ifdef XBEE_SERIAL_VERBOSE printf( "%s: %s failed (%lu initializing COM%u)\n", __FUNCTION__, "SetCommTimeouts", GetLastError(), serial->comport); #endif CloseHandle( hCom); return -EIO; } PurgeComm( hCom, PURGE_TXCLEAR | PURGE_TXABORT | PURGE_RXCLEAR | PURGE_RXABORT); serial->hCom = hCom; err = xbee_ser_baudrate( serial, baudrate); if (err) { serial->hCom = NULL; return err; } #ifdef XBEE_SERIAL_VERBOSE printf( "%s: SUCCESS COM%u opened (hCom=%p, baud=%u)\n", __FUNCTION__, serial->comport, hCom, baudrate); #endif return 0; }
static co_rc_t coserial_main(int argc, char *argv[]) { co_rc_t rc; co_module_t module; HANDLE out_handle, in_handle; int select_time; rc = handle_parameters(&g_daemon_parameters, argc, argv); if (!CO_OK(rc)) return rc; rc = co_reactor_create(&g_reactor); if (!CO_OK(rc)) return rc; co_debug("connecting to monitor"); module = CO_MODULE_SERIAL0 + g_daemon_parameters.index; rc = co_user_monitor_open(g_reactor, monitor_receive, g_daemon_parameters.instance, &module, 1, &g_monitor_handle); if (!CO_OK(rc)) return rc; if (g_daemon_parameters.filename_specified == PTRUE) { char name [strlen(g_daemon_parameters.filename) + 4+1]; DCB dcb; COMMTIMEOUTS commtimeouts = { 1, /* ReadIntervalTimeout */ 0, /* ReadTotalTimeoutMultiplier */ 0, /* ReadTotalTimeoutConstant */ 0, /* WriteTotalTimeoutMultiplier */ 0 }; /* WriteTotalTimeoutConstant */ if (g_daemon_parameters.filename[0] != '\\') { /* short windows name */ if (strncasecmp(g_daemon_parameters.filename, "COM", 3) != 0) co_terminal_print("warning: host serial device '%s' is not a COM port\n", g_daemon_parameters.filename); snprintf(name, sizeof(name), "\\\\.\\%s", g_daemon_parameters.filename); } else { /* windows full name device */ strncpy(name, g_daemon_parameters.filename, sizeof(name)); } co_debug("open device '%s'", name); out_handle = \ in_handle = CreateFile (name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); if (in_handle == INVALID_HANDLE_VALUE) { co_terminal_print_last_error(g_daemon_parameters.filename); return CO_RC(ERROR); } if (g_daemon_parameters.mode_specified == PTRUE) { co_debug("set mode: %s", g_daemon_parameters.mode); if (!GetCommState(in_handle, &dcb)) { co_terminal_print_last_error("GetCommState"); return CO_RC(ERROR); } /* Set defaults. user can overwrite ot */ dcb.fOutxCtsFlow = FALSE; /* Disable Handshake */ dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fRtsControl = RTS_CONTROL_ENABLE; if (!BuildCommDCB(g_daemon_parameters.mode, &dcb)) { /*co_terminal_print_last_error("colinux-serial-daemon: BuildCommDCB");*/ co_terminal_print("colinux-serial-daemon: error in mode parameter '%s'\n", g_daemon_parameters.mode); return CO_RC(ERROR); } if (!SetCommState(in_handle, &dcb)) { co_terminal_print_last_error("SetCommState"); return CO_RC(ERROR); } } else { if (!EscapeCommFunction(in_handle, SETDTR)) { co_terminal_print_last_error("Warning EscapeCommFunction DTR"); /* return CO_RC(ERROR); */ } if (!EscapeCommFunction(in_handle, SETRTS)) { co_terminal_print_last_error("Warning EscapeCommFunction RTS"); /* return CO_RC(ERROR); */ } } if (!SetCommTimeouts(in_handle, &commtimeouts)) { co_terminal_print_last_error("SetCommTimeouts"); return CO_RC(ERROR); } if (!SetupComm(in_handle, 2048, 2048)) { co_terminal_print_last_error("SetupComm"); return CO_RC(ERROR); } select_time = -1; } else { co_debug("std input/output"); out_handle = GetStdHandle(STD_OUTPUT_HANDLE); in_handle = GetStdHandle(STD_INPUT_HANDLE); select_time = 100; } co_debug("connected"); rc = co_winnt_reactor_packet_user_create(g_reactor, out_handle, in_handle, std_receive, &g_reactor_handle); if (!CO_OK(rc)) return rc; co_terminal_print("colinux-serial-daemon: running\n"); while (CO_OK(rc)) { rc = co_reactor_select(g_reactor, select_time); if (CO_RC_GET_CODE(rc) == CO_RC_BROKEN_PIPE) return CO_RC(OK); /* Normal, if linux shut down */ if (!g_daemon_parameters.filename_specified) if ( _kbhit() ) send_userinput(); } return -1; }
// 포트 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; }
extern "C" __declspec(dllexport) int GccOpenGps(int com_port, int rate) { wchar_t comport[10]; if(com_port >= 100) { logRawNmea = true; com_port -= 100; } else { logRawNmea = false; } if(com_port == 13) { wcscpy(comport, L"\\nmea.txt"); filemode = true; } else { swprintf(comport, L"COM%i:", com_port); filemode = false; } __hGpsPort = CreateFile(comport, GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); /* // for some reason sprintf did not work to write all these in one line ... if (com_port == 1) __hGpsPort = CreateFile(L"COM1:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 2) __hGpsPort = CreateFile(L"COM2:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 3) __hGpsPort = CreateFile(L"COM3:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 4) __hGpsPort = CreateFile(L"COM4:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 5) __hGpsPort = CreateFile(L"COM5:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 6) __hGpsPort = CreateFile(L"COM6:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 7) __hGpsPort = CreateFile(L"COM7:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 8) __hGpsPort = CreateFile(L"COM8:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 9) __hGpsPort = CreateFile(L"COM9:", GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 10) __hGpsPort = CreateFile(L"COM10:",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 11) __hGpsPort = CreateFile(L"COM11:",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 12) __hGpsPort = CreateFile(L"COM12:",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 13) __hGpsPort = CreateFile(L"COM13:",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); else if(com_port == 14) __hGpsPort = CreateFile(L"COM14:",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); */ if(__hGpsPort == INVALID_HANDLE_VALUE) { DWORD dwLastError = GetLastError(); switch(dwLastError) { case ERROR_ACCESS_DENIED: return -1; break; case ERROR_FILE_NOT_FOUND: return -2; break; default: return -3; break; } } if(!filemode) { // COM port setting DCB dcb; if (GetCommState(__hGpsPort,&dcb)) //fails on some devices with internal GPS - in these cases it's not necessarry anyway { // Set baud rate and other params dcb.BaudRate = (DWORD)rate; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; dcb.ByteSize = 8; // use defaults for other fields (found on web) dcb.fBinary = TRUE; dcb.fParity = FALSE; dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fDsrSensitivity = FALSE; dcb.fOutX = FALSE; dcb.fInX = FALSE; dcb.fNull = FALSE; dcb.fRtsControl = RTS_CONTROL_ENABLE; dcb.fAbortOnError = FALSE; if (SetCommState(__hGpsPort,&dcb) == 0) { return -5; } } // set mask which events to monitor SetCommMask(__hGpsPort, EV_RXCHAR); // set buffer sizes (defaults in Windows) SetupComm( __hGpsPort, 4096, 2048); // Clear all chars from COM PurgeComm(__hGpsPort,PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR); // Setup the comm timeouts. This is important: MAXDWORD for ReadIntervalTimeout means return immediately. COMMTIMEOUTS CommTimeOuts; CommTimeOuts.ReadIntervalTimeout = 10; CommTimeOuts.ReadTotalTimeoutMultiplier = 0; CommTimeOuts.ReadTotalTimeoutConstant = 300; CommTimeOuts.WriteTotalTimeoutMultiplier = 0; CommTimeOuts.WriteTotalTimeoutConstant = 10; if (SetCommTimeouts( __hGpsPort, &CommTimeOuts ) == 0) { return -6; } DWORD dwErrors; COMSTAT ComStat; ClearCommError(__hGpsPort,&dwErrors, &ComStat); } // reset read buffer __save_str = ""; __read_lock = false; if (logRawNmea) { FILE *file = fopen("\\tmp.txt", "w"); fprintf(file, ""); fclose(file); } //FILE *filex = fopen("\\debug.txt", "w"); //fprintf(filex, "debugfile\n"); HANDLE initfile = CreateFile(L"\\GccInitGps.txt", GENERIC_READ,FILE_SHARE_READ, NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(initfile != INVALID_HANDLE_VALUE) //file exists -> send init data to GPS device { char c; unsigned long r,w; BOOL a; while(1) { if(!ReadFile(initfile, &c, 1, &r, NULL) || r==0) break; for(int i=0; i<1000; i++) { a=WriteFile(__hGpsPort, &c, 1, &w, NULL); //w==0 if buffer full? //fprintf(filex, "read=%i char=%c written=%i ret=%i\n",r,c,w,a); if(w == 1) break; } } CloseHandle(initfile); } //fclose(filex); return 1; }
static void RS485_Configure_Status( void) { DCB dcb = { 0 }; COMMTIMEOUTS ctNew; dcb.DCBlength = sizeof(dcb); /* get current DCB settings */ if (!GetCommState(RS485_Handle, &dcb)) { fprintf(stderr, "Unable to get status from %s\n", RS485_Port_Name); RS485_Print_Error(); exit(1); } /* update DCB rate, byte size, parity, and stop bits size */ dcb.BaudRate = RS485_Baud; dcb.ByteSize = (unsigned char) RS485_ByteSize; dcb.Parity = (unsigned char) RS485_Parity; dcb.StopBits = (unsigned char) RS485_StopBits; /* update flow control settings */ dcb.fDtrControl = RS485_DTRControl; dcb.fRtsControl = RS485_RTSControl; /* dcb.fOutxCtsFlow = CTSOUTFLOW(TTYInfo); dcb.fOutxDsrFlow = DSROUTFLOW(TTYInfo); dcb.fDsrSensitivity = DSRINFLOW(TTYInfo); dcb.fOutX = XONXOFFOUTFLOW(TTYInfo); dcb.fInX = XONXOFFINFLOW(TTYInfo); dcb.fTXContinueOnXoff = TXAFTERXOFFSENT(TTYInfo); dcb.XonChar = XONCHAR(TTYInfo); dcb.XoffChar = XOFFCHAR(TTYInfo); dcb.XonLim = XONLIMIT(TTYInfo); dcb.XoffLim = XOFFLIMIT(TTYInfo); // DCB settings not in the user's control dcb.fParity = TRUE; */ if (!SetCommState(RS485_Handle, &dcb)) { fprintf(stderr, "Unable to set status on %s\n", RS485_Port_Name); RS485_Print_Error(); } /* configure the COM port timeout values */ ctNew.ReadIntervalTimeout = MAXDWORD; ctNew.ReadTotalTimeoutMultiplier = MAXDWORD; ctNew.ReadTotalTimeoutConstant = 1000; ctNew.WriteTotalTimeoutMultiplier = 0; ctNew.WriteTotalTimeoutConstant = 0; if (!SetCommTimeouts(RS485_Handle, &ctNew)) { RS485_Print_Error(); } /* Get rid of any stray characters */ if (!PurgeComm(RS485_Handle, PURGE_TXABORT | PURGE_RXABORT)) { fprintf(stderr, "Unable to purge %s\n", RS485_Port_Name); RS485_Print_Error(); } /* Set the Comm buffer size */ SetupComm(RS485_Handle, MAX_MPDU, MAX_MPDU); /* raise DTR */ if (!EscapeCommFunction(RS485_Handle, SETDTR)) { fprintf(stderr, "Unable to set DTR on %s\n", RS485_Port_Name); RS485_Print_Error(); } }