BOOL GetIniCommValues( _In_ LPWSTR pName, LPDCB pdcb, LPCOMMTIMEOUTS pcto ) { BOOL bRet = TRUE; LPWSTR pszEntry = NULL; if (bRet) { bRet = GetIniCommValuesFromRegistry (pName, &pszEntry); } if (bRet) { bRet = BuildCommDCB (pszEntry, pdcb); } if (bRet) { GetTransmissionRetryTimeoutFromRegistry (&pcto-> WriteTotalTimeoutConstant); pcto->WriteTotalTimeoutConstant*=1000; } FreeSplMem(pszEntry); return bRet; }
/** @fn int serial_io_init( const char* port, const char* strsettings ) ***************************************************************************** * @b Description: initialise a serial port communication ***************************************************************************** * @param port : port name * example 'COM7' * @param strsettings : port settings * example ; 'baud=115200 parity=N data=8 stop=1' ***************************************************************************** * @return file descriptor * -1 if error ***************************************************************************** **/ int serial_io_init( const char* port, const char* strsettings ) { HANDLE hCom = NULL; char strport[16]; snprintf( strport, sizeof( strport ), "\\\\.\\%s", port ); hCom = CreateFile( strport, GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, 0, NULL); if (hCom == INVALID_HANDLE_VALUE) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); dbg(1, "return (fd) : '-1' : serial_io_init error : '%s'\n", lpMsgBuf); LocalFree( lpMsgBuf ); // Free the buffer. return -1; } DCB dcb; ZeroMemory(&dcb, sizeof(DCB)); GetCommState(hCom, &dcb); BuildCommDCB( strsettings, &dcb); SetupComm(hCom, 4096, 4096); SetCommState(hCom, &dcb); COMMTIMEOUTS sCT; memset(&sCT, 0, sizeof(sCT)); sCT.ReadTotalTimeoutConstant = 10; SetCommTimeouts(hCom, &sCT); dbg(1, "serial_io_init return (fd) : '%d'\n", (int)hCom); return (int)hCom; }
/*------------------------------------------- | Name:setRs2322 | Description: | Parameters: | Return Type: | Comments: | See: ---------------------------------------------*/ int setRs232(uart_config* config){ COMMCONFIG commconfig; DWORD dwSize=sizeof(COMMCONFIG); char buffer[256]={0}; sprintf(buffer,"%s: baud=%d parity=%c data=%d stop=%d",USE_COM, config->speed, config->parity, config->data, config->stop); if(!GetCommConfig(hCom,&commconfig,&dwSize)) return -1; BuildCommDCB(buffer,&commconfig.dcb); //CommConfigDialog(USE_COM,NULL,&commconfig); if(!SetCommConfig(hCom,&commconfig,dwSize)) return -1; printf("com cfg: %s\n",buffer); memcpy(¤t_config,config,sizeof(uart_config)); return 0; }
int far pascal zBuildCommDCB( LPCSTR pp1, DCB far* pp2 ) { int r; SaveRegs(); /* ** Log IN Parameters (No Create/Destroy Checking Yet!) */ LogIn( (LPSTR)"APICALL:BuildCommDCB ++", (short)0, (short)0 ); /* ** Call the API! */ RestoreRegs(); GrovelDS(); r = BuildCommDCB(pp1,pp2); UnGrovelDS(); SaveRegs(); /* ** Log Return Code & OUT Parameters (No Create/Destroy Checking Yet!) */ LogOut( (LPSTR)"APIRET:BuildCommDCB int+LPCSTR+DCB far*+", r, pp1, pp2 ); RestoreRegs(); return( r ); }
/****************************************************************************** * Name: CCommDevice::InitPort * * Purpose: initializes the com port ******************************************************************************/ BOOL CCommDevice::InitPort( HANDLE hPort, int baud, char parity, int data, int stop) { DCB dcb; if( !GetCommState( hPort, (LPDCB)&dcb)) return FALSE; CString sMode; sMode.Format( "baud=%d parity=%c data=%d stop=%d", baud, parity, data, stop); if( !BuildCommDCB( (LPCTSTR)sMode, &dcb)) return FALSE; dcb.fBinary = 1; dcb.fErrorChar = 0; dcb.fAbortOnError = TRUE; //dcb.XonLim = 2048; //dcb.XoffLim = 512; dcb.XonChar = 17; // '\x11' dcb.XoffChar = 19; // '\x13' dcb.EofChar = '\r'; dcb.EvtChar = '\r'; dcb.fDsrSensitivity = 0; dcb.fNull = 0; if( !SetCommState( hPort, (LPDCB)&dcb)) return FALSE; return TRUE; }
/** * @brief This function initializes the serial port for both directions (reading/writing) with fixed parameters: * \n baud=38400, parity=N, data=8, stop=1 * @param *serialPort is a pointer to the name of the serial port * @return TRUE if success, FALSE in case of error. */ BOOL initSerial(CHAR *serialPort) { COMMTIMEOUTS timeouts; int rc; DCB dcbStruct; CHAR msgTextBuf[256]; // open the comm port. comPort = CreateFile(serialPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, NULL); if (comPort == INVALID_HANDLE_VALUE) { printf("Unable to open %s. \n", serialPort); return FALSE; } // get the current DCB, and adjust a few bits to our liking. memset(&dcbStruct, 0, sizeof(dcbStruct)); dcbStruct.DCBlength = sizeof(dcbStruct); // printf("dcbStruct.DCBlength(): %ld \n", dcbStruct.DCBlength); rc = GetCommState(comPort, &dcbStruct); if (rc == 0) { printf("\nGetCommState(): "); printf(getLastErrorText(msgTextBuf, sizeof(msgTextBuf))); return FALSE; } // http://msdn.microsoft.com/en-us/library/windows/desktop/aa363143(v=vs.85).aspx BuildCommDCB("baud=38400 parity=N data=8 stop=1", &dcbStruct); rc = SetCommState(comPort, &dcbStruct); // If the function fails, the return value is zero. if (rc == 0) { printf("\nSetCommState(): "); printf(getLastErrorText(msgTextBuf, sizeof(msgTextBuf))); return FALSE; } // Retrieve the timeout parameters for all read and write operations on the port. GetCommTimeouts (comPort, &timeouts); timeouts.ReadIntervalTimeout = 250; timeouts.ReadTotalTimeoutMultiplier = 1; timeouts.ReadTotalTimeoutConstant = 500; timeouts.WriteTotalTimeoutMultiplier = 1; timeouts.WriteTotalTimeoutConstant = 2500; rc = SetCommTimeouts(comPort, &timeouts); // If the function fails, the return value is zero. if (rc == 0) { printf("\nSetCommTimeouts(): "); printf(getLastErrorText(msgTextBuf, sizeof(msgTextBuf))); return FALSE; } return TRUE; }
static SERIALPORT *serial_open(const char *device){ HANDLE fh; DCB dcb={sizeof(DCB)}; COMMTIMEOUTS timeouts; SERIALPORT *port; fh = CreateFile(device,GENERIC_READ|GENERIC_WRITE,0,NULL, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if (!fh) return NULL; port = malloc(sizeof(SERIALPORT)); ZeroMemory(port, sizeof(SERIALPORT)); port->fh = fh; /* save current port settings */ GetCommState(fh,&port->dcb_save); GetCommTimeouts(fh,&port->timeouts_save); dcb.DCBlength=sizeof(DCB); BuildCommDCB("96,n,8,1",&dcb); SetCommState(fh,&dcb); ZeroMemory(&timeouts,sizeof(timeouts)); timeouts.ReadTotalTimeoutConstant=1; timeouts.WriteTotalTimeoutConstant=1; SetCommTimeouts(fh,&timeouts); serial_flush(port); return port; }
// configure serial port bool sconfig(char* fmt) { DCB dcb; COMMTIMEOUTS cmt; // clear dcb memset(&dcb,0,sizeof(DCB)); dcb.DCBlength=sizeof(DCB); // configure serial parameters if(!BuildCommDCB(fmt,&dcb)) return false; dcb.fOutxCtsFlow=0; dcb.fOutxDsrFlow=0; dcb.fDtrControl=0; dcb.fOutX=0; dcb.fInX=0; dcb.fRtsControl=0; if(!SetCommState(h_serial,&dcb)) return false; // configure buffers if(!SetupComm(h_serial,1024,1024)) return false; // configure timeouts GetCommTimeouts(h_serial,&cmt); memcpy(&restore,&cmt,sizeof(cmt)); cmt.ReadIntervalTimeout=100; cmt.ReadTotalTimeoutMultiplier=100; cmt.ReadTotalTimeoutConstant=100; cmt.WriteTotalTimeoutConstant=100; cmt.WriteTotalTimeoutMultiplier=100; if(!SetCommTimeouts(h_serial,&cmt)) return false; return true; }
bool Open(qCtx *ctx, qStr *out, CStr port, CStr dcb_def) { DCB dcb; HANDLE tCom; tCom = CreateFile( port, GENERIC_READ | GENERIC_WRITE, 0, // comm devices must be opened w/exclusive-access NULL, // no security attributes OPEN_EXISTING, // comm devices must use OPEN_EXISTING 0, // not overlapped I/O NULL // hTemplate must be NULL for comm devices ); if (tCom == INVALID_HANDLE_VALUE) { ctx->ThrowF(out, 601, "Invalid comm port. %y", GetLastError()); return false; } GetCommState(tCom, &dcb); if (!dcb_def.IsEmpty() && (!BuildCommDCB(dcb_def, &dcb) || !SetCommState(tCom, &dcb)) ) { ctx->ThrowF(out, 602, "Invalid comm definition parameter(s). %y", GetLastError()); return false; } myCom = tCom; return true; }
// configures port from string of format // baudrate,parity,databits,stopbits // example // 9600,n,8,1 int serial_params( char* params ) { DCB dcb; COMMTIMEOUTS cmt; memset( &dcb, 0, sizeof( DCB ) ); dcb.DCBlength = sizeof( DCB ); // Configure serial parameters //printf( "BuildCommDCB\n" ); if( !BuildCommDCB( params, &dcb ) ) return( -1 ); //printf( "SetCommState\n" ); dcb.fOutxCtsFlow = 0; dcb.fOutxDsrFlow = 0; dcb.fDtrControl = 0; dcb.fOutX = 0; dcb.fInX = 0; dcb.fRtsControl = 0; if( !SetCommState( h_serial, &dcb ) ) return( -1 ); // Configure buffers //printf( "SetupComm\n" ); if( !SetupComm( h_serial, 1024, 1024) ) return( -1 ); // Configure timeouts cmt.ReadIntervalTimeout = 1000; cmt.ReadTotalTimeoutMultiplier = 1000; cmt.ReadTotalTimeoutConstant = 1000; cmt.WriteTotalTimeoutConstant = 1000; cmt.WriteTotalTimeoutMultiplier = 1000; if( !SetCommTimeouts( h_serial, &cmt ) ) return( -1 ); return( 0 ); }
bool CSerialPort::Open( LPCTSTR lpszComPort,LPCTSTR lpszConString ,int delay_us) { CString sPort; sPort.Format(_T("\\\\.\\%s"), lpszComPort); m_hComm = CreateFile(sPort, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,0,0); if (m_hComm == INVALID_HANDLE_VALUE) { CString str; GetErrorStr(str); LogMessage(str); return false; } Delay_US = delay_us; // Set Com Settings DCB dcb; FillMemory(&dcb, sizeof(dcb), 0); dcb.DCBlength = sizeof(dcb); if (!BuildCommDCB(lpszConString, &dcb)) { // Couldn't build the DCB. Usually a problem // with the communications specification string. CString str; GetErrorStr(str); LogMessage(str); LogMessage("Seri Port Hatasý. (BuildComDCB)"); CloseHandle(m_hComm); m_hComm = NULL; return false; } if (!SetCommState(m_hComm, &dcb)) { CString str; GetErrorStr(str); LogMessage(str); LogMessage("Seri Port Hatasý. (SetCommState)"); CloseHandle(m_hComm); m_hComm = NULL; return false; } COMMTIMEOUTS cm; FillMemory(&cm, sizeof(cm), 0); cm.ReadIntervalTimeout = 10; cm.ReadTotalTimeoutConstant = 10; if(!SetCommTimeouts(m_hComm,&cm)) { CString str; GetErrorStr(str); LogMessage(str); LogMessage("Seri Port Hatasý. (SetCommTimeouts)"); CloseHandle(m_hComm); m_hComm = NULL; return false; } LogMessage("Seri port açýldý."); return true; }
//------------------------------------------------------------------------------ bool open_com_port( HANDLE &hCOM_HANDLE, int i_com_port, int i_baud_rate) { if ( hCOM_HANDLE != NULL && hCOM_HANDLE != INVALID_HANDLE_VALUE ) { PurgeComm( hCOM_HANDLE, PURGE_TXABORT); PurgeComm( hCOM_HANDLE, PURGE_RXABORT); PurgeComm( hCOM_HANDLE, PURGE_TXCLEAR); PurgeComm( hCOM_HANDLE, PURGE_RXCLEAR); CloseHandle( hCOM_HANDLE); hCOM_HANDLE = NULL; } char c_com[50]; ::sprintf(c_com, "\\\\.\\COM%d", i_com_port); hCOM_HANDLE = ::CreateFile( c_com, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if( hCOM_HANDLE == INVALID_HANDLE_VALUE ) { //ShowMessage(" COM" + IntToStr( i_com_port) + " is used by other program."); GC_TRACE("<EfuseWriter> open_com_port(): Com %d is used by other program", i_com_port); hCOM_HANDLE = NULL; return false; } if( ::SetupComm(hCOM_HANDLE, 8192, 8192)==FALSE ) return false; if( ::PurgeComm(hCOM_HANDLE, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR)==FALSE ) return false; COMMTIMEOUTS TimeOut; TimeOut.ReadIntervalTimeout = 0; TimeOut.ReadTotalTimeoutMultiplier = 1; TimeOut.ReadTotalTimeoutConstant = 700; TimeOut.WriteTotalTimeoutMultiplier = 1; TimeOut.WriteTotalTimeoutConstant = 700; SetCommTimeouts(hCOM_HANDLE, &TimeOut); char c_dcb[50]; ::sprintf( c_dcb, "%d,n,8,1", i_baud_rate); BuildCommDCB( c_dcb, &dcb ); SetCommState( hCOM_HANDLE, &dcb ); return true; }
void openCOMPort(int port) { char portString[100]; sprintf(portString, "\\\\.\\COM%i", port); hComm = CreateFile(portString, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, NULL, 0); if (hComm == INVALID_HANDLE_VALUE) { printf("port open error\n"); exit(1); } COMMTIMEOUTS commTimeouts; commTimeouts.ReadIntervalTimeout = MAXDWORD; commTimeouts.ReadTotalTimeoutMultiplier = MAXDWORD ; commTimeouts.ReadTotalTimeoutConstant = 1; commTimeouts.WriteTotalTimeoutMultiplier = 1000; commTimeouts.WriteTotalTimeoutConstant = 1000; if (!SetCommTimeouts(hComm, &commTimeouts)) { printf("SetCommTimeouts error\n"); exit(1); } DCB dcb; if (!GetCommState(hComm, &dcb)) { printf("GetCommState error\n"); exit(1); } if (!BuildCommDCB("baud=115200 parity=N data=8 stop=1", &dcb)) { printf("BuildCommDCB() error\n"); exit(1); } dcb.BaudRate = CBR_115200; dcb.fBinary = TRUE; dcb.fParity = FALSE; dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fDtrControl = DTR_CONTROL_DISABLE; dcb.fDsrSensitivity = FALSE; dcb.fOutX = FALSE; dcb.fInX = FALSE; dcb.fErrorChar = FALSE; dcb.fNull = FALSE; dcb.fRtsControl = RTS_CONTROL_DISABLE; dcb.fAbortOnError = FALSE; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; if (!SetCommState(hComm, &dcb)) { printf("SetCommState() error\n"); exit(1); } PurgeComm(hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT); DWORD threadID; HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) commThread, NULL, 0, &threadID); if (!thread) { printf("CreateThread() error\n"); exit(1); } }
BOOL PrnOpen(PCHAR DevName) { char Temp[MAXPATHLEN], *c; DCB dcb; DWORD DErr; COMMTIMEOUTS ctmo; OSVERSIONINFO osvi; strncpy_s(Temp, sizeof(Temp),DevName, _TRUNCATE); c = Temp; while (*c != '\0' && *c != ':') { c++; } *c = '\0'; LPTFlag = (Temp[0]=='L') || (Temp[0]=='l'); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osvi); if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) { // ネットワーク共有にマップされたデバイスが相手の場合、こうしないといけないらしい (2011.01.25 maya) // http://logmett.com/forum/viewtopic.php?f=2&t=1383 // http://msdn.microsoft.com/en-us/library/aa363858(v=vs.85).aspx#5 PrnID = CreateFile(Temp,GENERIC_WRITE | FILE_READ_ATTRIBUTES, FILE_SHARE_READ,NULL,CREATE_ALWAYS, 0,NULL); } else { // 9x では上記のコードでうまくいかないので従来通りの処理 PrnID = CreateFile(Temp,GENERIC_WRITE, 0,NULL,OPEN_EXISTING, 0,NULL); } if (PrnID == INVALID_HANDLE_VALUE) { return FALSE; } if (GetCommState(PrnID,&dcb)) { BuildCommDCB(DevName,&dcb); SetCommState(PrnID,&dcb); } ClearCommError(PrnID,&DErr,NULL); if (! LPTFlag) { SetupComm(PrnID,0,CommOutQueSize); } /* flush output buffer */ PurgeComm(PrnID, PURGE_TXABORT | PURGE_TXCLEAR); memset(&ctmo,0,sizeof(ctmo)); ctmo.WriteTotalTimeoutConstant = 1000; SetCommTimeouts(PrnID,&ctmo); if (! LPTFlag) { EscapeCommFunction(PrnID,SETDTR); } return TRUE; }
static const char * SerialInit(struct serial *sn, const char *Device, enum SerialBaud Baud, enum SerialStopbits StopBits, enum SerialProtocol Protocol, enum SerialParity Parity, enum SerialDatabits DataBits, int dowrite) { char mydevice[50]; if(Device[0] != '\\') snprintf(mydevice, sizeof(mydevice), "\\\\.\\%s", Device); else mydevice[0] = 0; if((sn->Stream = CreateFile(mydevice[0] ? mydevice : Device, dowrite ? GENERIC_WRITE|GENERIC_READ : GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE) return "could not create file"; memset(&sn->Termios, 0, sizeof(sn->Termios)); GetCommState(sn->Stream, &sn->Termios); DCB dcb; memset(&dcb, 0, sizeof(dcb)); char str[100]; snprintf(str,sizeof(str), "baud=%d parity=%c data=%d stop=%d xon=%s octs=%s rts=%s", Baud, Parity, DataBits, StopBits, Protocol == SPAPROTOCOL_XON_XOFF ? "on" : "off", Protocol == SPAPROTOCOL_RTS_CTS ? "on" : "off", Protocol == SPAPROTOCOL_RTS_CTS ? "on" : "off"); #ifdef DEBUG fprintf(stderr, "COM Settings: %s\n", str); #endif COMMTIMEOUTS ct = {MAXDWORD, 0, 0, 0, 0}; if(!BuildCommDCB(str, &dcb)) { CloseHandle(sn->Stream); return "creating device parameters failed"; } else if(!SetCommState(sn->Stream, &dcb)) { CloseHandle(sn->Stream); return "setting device parameters failed"; } else if(!SetCommTimeouts(sn->Stream, &ct)) { CloseHandle(sn->Stream); return "setting timeouts failed"; } return 0; }
void CUartChannel::SetupBaud(char *setting) { DCB dcb; sscanf(setting, "%d", &this->m_baud); if(this->IsOpened() == FALSE) return; memset( &dcb, 0, sizeof(DCB) ); dcb.DCBlength = sizeof(DCB); if (!BuildCommDCB(setting, &dcb)) return; SetCommState(this->m_Hcomm, &dcb); }
static HANDLE ComOpen(const char *path, uint32_t baud, uint8_t parity, uint32_t flags) { COMMTIMEOUTS CommTimeouts; DCB dcb; wchar_t baud_s[50]; wsprintf(baud_s, L"baud=%d parity=%s data=8 stop=1",baud, parity == PARITY::EVEN ? "E" : (parity == PARITY::ODD ? "O" : "N" ) ); // get a handle to the port HANDLE hCom = CreateFileA(path, // communication port path GENERIC_READ | GENERIC_WRITE, // read/write types 0, // comm devices must be opened with exclusive access NULL, // no security attributes OPEN_EXISTING, // comm devices must use OPEN_EXISTING flags, // flags 0); // template must be 0 for comm devices if (hCom == INVALID_HANDLE_VALUE) { HandleLastError("CreateFile"); return hCom; } // set the timeout values CommTimeouts.ReadIntervalTimeout = 1; CommTimeouts.ReadTotalTimeoutMultiplier = 0; CommTimeouts.ReadTotalTimeoutConstant = 0; CommTimeouts.WriteTotalTimeoutMultiplier = 0; CommTimeouts.WriteTotalTimeoutConstant = 0; // configure if (SetCommTimeouts(hCom, &CommTimeouts)) { //if (GetCommState(hCom, &dcb)) //{ //dcb.fOutxCtsFlow = FALSE; //dcb.fRtsControl = RTS_CONTROL_ENABLE; if (BuildCommDCB(baud_s, &dcb)) { SetCommState(hCom, &dcb); // normal operation... continue } //} } return hCom; }
int MySerial::Open(MyUart *com) { hCom = CreateFile(com->port_name,//COM口 GENERIC_READ|GENERIC_WRITE, //允许读和写 0, //独占方式 NULL, OPEN_EXISTING, //打开而不是创建 0, //同步方式 NULL); if( hCom == (HANDLE)-1 ) { return -1; } COMMTIMEOUTS timeout; memset(&timeout,0,sizeof(COMMTIMEOUTS)); timeout.ReadIntervalTimeout = 10; timeout.ReadTotalTimeoutMultiplier=1; timeout.ReadTotalTimeoutConstant=1; timeout.WriteTotalTimeoutMultiplier=1; timeout.WriteTotalTimeoutConstant=1; SetCommTimeouts(hCom, &timeout); SetCommMask(hCom, EV_RXCHAR);// 把间隔超时设为最大,把总超时设为0将导致ReadFile立即返回并完成操作 DCB dcb; memset(&dcb,0,sizeof(dcb)); char buf[512] ={0}; if(com->dcb.Parity==0) com->dcb.Parity = 78; else if(com->dcb.Parity==1) com->dcb.Parity = 79; else if(com->dcb.Parity==2) com->dcb.Parity = 69; sprintf(buf,"%d,%c,%d,%d",com->dcb.BaudRate, com->dcb.Parity, com->dcb.ByteSize, com->dcb.StopBits); if( !BuildCommDCB(buf,&dcb) ) return -1; if( !SetCommState(hCom,&dcb) ) return -1; SetupComm(hCom, 2048, 2048);//设置缓冲区 PurgeComm(hCom, PURGE_TXCLEAR|PURGE_RXCLEAR|PURGE_TXABORT|PURGE_RXABORT); return 0; }
/** * 友元函数 * 接收器工作线程 * 不断获取从串口接收到的数据包并产生消息 * 单从串口 EnOcean USB 抓包器不能反馈信号强度信息 * */ static DWORD WINAPI Thread(LPVOID thiz) { ZYSSniffer *pThiz = (ZYSSniffer *) thiz; if (!pThiz->m_cCp.IsEmpty()) { HANDLE h = CreateFile(pThiz->m_cCp, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (h != INVALID_HANDLE_VALUE) { COMMTIMEOUTS t; DCB d; GetCommTimeouts(h, &t); t.ReadIntervalTimeout =MAXDWORD; t.ReadTotalTimeoutMultiplier= 0; t.ReadTotalTimeoutConstant = 0; SetCommTimeouts(h, &t); GetCommState(h, &d); BuildCommDCB("57600,n,8,1", &d); if (SetCommState(h, &d)) { PurgeComm(h, PURGE_TXCLEAR | PURGE_RXCLEAR); pThiz->m_bRun = TRUE; while (pThiz->m_bRun) { BYTE b; LONG c; if (ReadFile(h, &b, 1, (LPDWORD) &c, 0)) { if (c) { Parse(&pThiz->m_cPack, b); if (pThiz->m_cPack.s==21) { INT daddr = pThiz->m_cPack.daddr[3] | pThiz->m_cPack.daddr[2] << 8 | pThiz->m_cPack.daddr[1] << 16 | pThiz->m_cPack.daddr[0] << 24; ::PostMessage(pThiz->m_hWnd, WM_ZYSSNIFFER_DATA, daddr, MAKEWORD(pThiz->m_cPack.sstat, pThiz->m_cPack.ddata)); pThiz->m_cPack.s = 0; } } } else { break; } } } CloseHandle(h); } } ::PostMessage(pThiz->m_hWnd, WM_ZYSSNIFFER_STAT, 0, 0); return 0L; }
void serialport_setbaudrate(unsigned int baudrate) { DWORD br = 0; switch(baudrate) { case 9600: br = CBR_9600; break; case 14400: br = CBR_14400; break; case 19200: br = CBR_19200; break; case 38400: br = CBR_38400; break; case 56000: br = CBR_56000; break; case 57600: br = CBR_57600; break; case 115200: br = CBR_115200; break; case 128000: br = CBR_128000; break; case 230400: br = CBR_230400; break; case 256000: br = CBR_256000; break; case 512000: br = CBR_512000; break; case 460800: br = CBR_460800; break; case 921600: br = CBR_921600; break; } if (br == 0) { LOGWARN("unsupported baud rate: %d, using 115200", baudrate); br = CBR_115200; } memset(&sDCB, 0, sizeof(DCB)); BuildCommDCB("baud=9600 parity=N data=8 stop=1",&sDCB); sDCB.DCBlength = sizeof(DCB); sDCB.BaudRate = br; sDCB.fBinary = TRUE; sDCB.fParity = FALSE; // sDCB.fOutxCtsFlow = TRUE; sDCB.fDtrControl = DTR_CONTROL_DISABLE; sDCB.fDsrSensitivity= FALSE; sDCB.fRtsControl = RTS_CONTROL_DISABLE; sDCB.ByteSize = 8; sDCB.StopBits = ONESTOPBIT; sDCB.fAbortOnError = FALSE; sDCB.fOutX = FALSE; sDCB.fInX = FALSE; if (!SetCommState(sPort, &sDCB)) { LOGDEBUG("SetCommState call failed"); } }
__bool CSerialPort::setup_dcb(const char *setting, DCB *dcb) { DCB setDCB; memset(&setDCB, 0, sizeof(DCB)); setDCB.DCBlength = sizeof(DCB); if(!BuildCommDCB(setting, &setDCB)){ return __false; } *dcb = setDCB; dcb->DCBlength = sizeof(DCB); dcb->fBinary = TRUE; // dcb->fParity = TRUE; dcb->fOutxCtsFlow = FALSE; dcb->fOutxDsrFlow = FALSE; dcb->fDtrControl = DTR_CONTROL_ENABLE; dcb->fDsrSensitivity = FALSE; dcb->fTXContinueOnXoff = TRUE; dcb->fOutX = FALSE; dcb->fInX = FALSE; dcb->fErrorChar = FALSE; dcb->fNull = FALSE; dcb->fRtsControl = RTS_CONTROL_ENABLE; dcb->fAbortOnError = FALSE; dcb->fDummy2 = 0; dcb->wReserved = 0; dcb->XonLim = 0; dcb->XoffLim = 0; // dcb->ByteSize = setDCB.ByteSize; // dcb->Parity = setDCB.Parity; // dcb->StopBits = setDCB.StopBits; // dcb->XonChar = ; // dcb->XoffChar = // dcb->ErrorChar = // dcb->EofChar = // dcb->EvtChar = // dcb->wReserved1 = // utils_trace("%08x\n", *((DWORD*)dcb + 2)); return __true; }
//--------------------------------------------------------------------------- void __fastcall TForm1::FormCreate(TObject *Sender) { DCB dcbCommPort; // abre a porta COM correspondente e inicializada abaixo hComm = CreateFile("COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0); // se a porta COM não puder ser aberta , finaliza o programa if(hComm == INVALID_HANDLE_VALUE) Application->Terminate(); // seta os tempos de saída GetCommTimeouts(hComm,&ctmoOld); ctmoNew.ReadTotalTimeoutConstant = 100; ctmoNew.ReadTotalTimeoutMultiplier = 0; ctmoNew.WriteTotalTimeoutMultiplier = 0; ctmoNew.WriteTotalTimeoutConstant = 0; SetCommTimeouts(hComm, &ctmoNew); // ajusta a taxa de tranferencia, a paridade, o tamanho da palavra, // e os bits de parada // ha outras maneiras de fazer esta inicialização de tempos de saída //mas esta que utilizamos é a mais fácil. dcbCommPort.DCBlength = sizeof(DCB); GetCommState(hComm, &dcbCommPort); BuildCommDCB("9600,N,8,1", &dcbCommPort); SetCommState(hComm, &dcbCommPort); // Ativa a thread , e inicializamos com "false" o argumento , porque // funciona melhor com ele suspendido. ReadThread = new TRead(false); }
void SerialPort::Open(const char * port) { mHandle = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if(mHandle == INVALID_HANDLE_VALUE) { //ACE_DEBUG(( LM_ERROR, "Failed to open port \"%C\"\n", port )); return; } //SetupComm(portHandle, 4096, 4096)); DCB dcb; GetCommState(mHandle, &dcb); // get existing settings BuildCommDCB("baud=19200 parity=N data=8 stop=1", &dcb); // set baud rate etc. if(0 == SetCommState(mHandle, &dcb)) // apply modified settings { //ACE_DEBUG(( LM_ERROR, "SetCommState failed\n" )); return; } COMMTIMEOUTS cts; cts.ReadIntervalTimeout = MAXDWORD; cts.ReadTotalTimeoutConstant = 0; cts.ReadTotalTimeoutMultiplier = 0; cts.WriteTotalTimeoutConstant = 0; cts.WriteTotalTimeoutMultiplier = 0; if(0 == SetCommTimeouts(mHandle, &cts)) { //ACE_DEBUG(( LM_ERROR, "SetCommTimeouts failed\n" )); return; } std::cerr << "Open ok" << std::endl; }
int main(int argc, char **argv) { HANDLE comHandle; int bytesWrittenCount; BOOL success; DCB dcb; char buf[512]; int row, col, font, type, just; if(argc < 2) { fprintf(stderr, "usage: %s comfile:\n", argv[0]); exit(EXIT_FAILURE); } comHandle = CreateFile(argv[1], GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL ); if (comHandle == INVALID_HANDLE_VALUE) { fprintf(stderr, "failed to CreateFile(%s), %d\n", argv[1], GetLastError()); exit(EXIT_FAILURE); } success = GetCommState(comHandle, &dcb); if (!success) { fprintf(stderr, "GetCommState failed, %d\n", GetLastError()); exit(EXIT_FAILURE); } BuildCommDCB("baud=38400 parity=N data=8 stop=1", &dcb ); success = SetCommState(comHandle, &dcb); if (!success) { fprintf(stderr, "SetCommState failed, %d\n", GetLastError()); exit(EXIT_FAILURE); } sprintf(buf, "%cCFF007F%c", 1, 3); success = WriteFile(comHandle, buf, strlen(buf), &bytesWrittenCount, 0); if (!success) { fprintf(stderr, "WriteFile failed, %d\n", GetLastError()); exit(EXIT_FAILURE); } CloseHandle(comHandle); }
//------------------------------------------------------------------------------ bool set_com_port( HANDLE &hCOM_HANDLE, int i_baud_rate) { if( hCOM_HANDLE==INVALID_HANDLE_VALUE ) { hCOM_HANDLE = NULL; return false; } if( hCOM_HANDLE==NULL ) { return false; } if ( PurgeComm( hCOM_HANDLE, PURGE_TXABORT)==0 || PurgeComm( hCOM_HANDLE, PURGE_RXABORT)==0 || PurgeComm( hCOM_HANDLE, PURGE_TXCLEAR)==0 || PurgeComm( hCOM_HANDLE, PURGE_RXCLEAR)==0 ) { return false; } if( ::SetupComm(hCOM_HANDLE, 8192, 8192)==FALSE ) return false; if( ::PurgeComm(hCOM_HANDLE, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR)==FALSE ) return false; COMMTIMEOUTS TimeOut; TimeOut.ReadIntervalTimeout = 0; TimeOut.ReadTotalTimeoutMultiplier = 1; TimeOut.ReadTotalTimeoutConstant = 700; TimeOut.WriteTotalTimeoutMultiplier = 1; TimeOut.WriteTotalTimeoutConstant = 700; SetCommTimeouts( hCOM_HANDLE, &TimeOut); char c_dcb[50]; ::sprintf( c_dcb, "%d,n,8,1", i_baud_rate); BuildCommDCB( c_dcb, &dcb ); SetCommState( hCOM_HANDLE, &dcb ); return true; }
void TFComm::SetCommPort(commport_t commport) { switch(commport) { case CMPT_RS232: #ifdef USING_VICTOR_COMM_CONTROL YbCommDevice1->Baud = TYbCommDevice::br115200; YbCommDevice1->Parity = TYbCommDevice::ptNoParity; YbCommDevice1->StopBits = TYbCommDevice::sbOneStopBit; YbCommDevice1->ByteSize = 8; #endif BuildCommDCB("baud=115200 parity=N data=8 stop=1", &dcb); break; case CMPT_SOCKET: ClientSocket->Host = FIPServer; ClientSocket->Port = FIPPort; break; } m_CurCommPort = commport; }
/*================================================================= * Function ID : SetState * Input : int nBaud, char cParity, int nDataBit, int nStopBit * Output : * Author : * Date : 2006 2 * Return : TRUE/FALSE * Description : 设置串口属性 * Notice : * : * *=================================================================*/ bool CComSmart::SetState(int nBaud, char cParity, int nDataBit, int nStopBit) { TCHAR szDCB[64]; DCB dcb; ZeroMemory(&dcb, sizeof(dcb)); dcb.DCBlength = sizeof(dcb); wsprintf(szDCB, "baud=%d parity=%c data=%d stop=%d", nBaud, cParity, nDataBit, nStopBit); if( !BuildCommDCB(szDCB, &dcb) ) { sprintf(m_szErrorText,"BuildCommDCB()出错[%ld]!", GetLastError()); return false; } if( !SetCommState(m_handle, &dcb) ) { sprintf(m_szErrorText,"SetCommState()出错[%ld]!", GetLastError()); return false; } return true; }
bool SerialPort::Open(const wxString path,const DWORD baud_rate) { Close(); com = CreateFile(path.wc_str(),GENERIC_READ | GENERIC_WRITE,NULL,NULL,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL); if(com == INVALID_HANDLE_VALUE){ Close(); return false; } memset(&dcb,0,sizeof(dcb)); wxString def; def.Printf(wxT("%d,n,8,1"),baud_rate); BuildCommDCB(def.wc_str(),&dcb); if(!SetCommState(com,&dcb)){ Close(); return false; } memset(&timeouts,0,sizeof(timeouts)); timeouts.ReadIntervalTimeout = MAXDWORD; timeouts.ReadTotalTimeoutConstant = 0; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 0; timeouts.WriteTotalTimeoutMultiplier = 0; if(!SetCommTimeouts(com,&timeouts)){ Close(); return false; } memset(&overlapped,0,sizeof(overlapped)); overlapped.Offset = 0; overlapped.OffsetHigh = 0; overlapped.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL); 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; }
// // Initialize the port. This can be port 1 to 4. // BOOL CSerialPort::InitPort(CWnd* pPortOwner, // the owner (CWnd) of the port (receives message) UINT portnr, // portnumber (1..4) UINT baud, // baudrate char parity, // parity UINT databits, // databits UINT stopbits, // stopbits DWORD dwCommEvents, // EV_RXCHAR, EV_CTS etc UINT writebuffersize) // size to the writebuffer { //assert(portnr > 0 && portnr < 5); assert(pPortOwner != NULL); // if the thread is alive: Kill if (m_bThreadAlive) { do { SetEvent(m_hShutdownEvent); } while (m_bThreadAlive); TRACE("Thread ended\n"); } // create events if (m_ov.hEvent != NULL) ResetEvent(m_ov.hEvent); m_ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (m_hWriteEvent != NULL) ResetEvent(m_hWriteEvent); m_hWriteEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (m_hShutdownEvent != NULL) ResetEvent(m_hShutdownEvent); m_hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL); // initialize the event objects m_hEventArray[0] = m_hShutdownEvent; // highest priority m_hEventArray[1] = m_ov.hEvent; m_hEventArray[2] = m_hWriteEvent; // initialize critical section InitializeCriticalSection(&m_csCommunicationSync); // set buffersize for writing and save the owner m_pOwner = pPortOwner; if (m_szWriteBuffer != NULL) delete [] m_szWriteBuffer; m_szWriteBuffer = new char[writebuffersize]; m_nPortNr = portnr; m_nWriteBufferSize = writebuffersize; m_dwCommEvents = dwCommEvents; BOOL bResult = FALSE; char *szPort = new char[50]; char *szBaud = new char[50]; // now it critical! EnterCriticalSection(&m_csCommunicationSync); // if the port is already opened: close it if (m_hComm != NULL) { CloseHandle(m_hComm); m_hComm = NULL; } // prepare port strings sprintf(szPort, "COM%d", portnr); sprintf(szBaud, "baud=%d parity=%c data=%d stop=%d", baud, parity, databits, stopbits); // get a handle to the port m_hComm = CreateFile(szPort, // communication port string (COMX) GENERIC_READ | GENERIC_WRITE, // read/write types 0, // comm devices must be opened with exclusive access NULL, // no security attributes OPEN_EXISTING, // comm devices must use OPEN_EXISTING FILE_FLAG_OVERLAPPED, // Async I/O 0); // template must be 0 for comm devices if (m_hComm == INVALID_HANDLE_VALUE) { // port not found delete [] szPort; delete [] szBaud; return FALSE; } // set the timeout values m_CommTimeouts.ReadIntervalTimeout = 1000; m_CommTimeouts.ReadTotalTimeoutMultiplier = 1000; m_CommTimeouts.ReadTotalTimeoutConstant = 1000; m_CommTimeouts.WriteTotalTimeoutMultiplier = 1000; m_CommTimeouts.WriteTotalTimeoutConstant = 1000; // configure if (SetCommTimeouts(m_hComm, &m_CommTimeouts)) { if (SetCommMask(m_hComm, dwCommEvents)) { if (GetCommState(m_hComm, &m_dcb)) { m_dcb.fRtsControl = RTS_CONTROL_ENABLE; // set RTS bit high! if (BuildCommDCB(szBaud, &m_dcb)) { if (SetCommState(m_hComm, &m_dcb)) ; // normal operation... continue else ProcessErrorMessage("SetCommState()"); } else ProcessErrorMessage("BuildCommDCB()"); } else ProcessErrorMessage("GetCommState()"); } else ProcessErrorMessage("SetCommMask()"); } else ProcessErrorMessage("SetCommTimeouts()"); delete [] szPort; delete [] szBaud; // flush the port PurgeComm(m_hComm, PURGE_RXCLEAR | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_TXABORT); // release critical section LeaveCriticalSection(&m_csCommunicationSync); TRACE("Initialisation for communicationport %d completed.\nUse Startmonitor to communicate.\n", portnr); return TRUE; }