int diag_tty_break(struct diag_l0_device *dl0d, const int ms) { HANDLE hd; long h; /* * I'm going through this convoluted two-step conversion * to avoid compiler warnings: */ h = get_osfhandle(dl0d->fd); hd = (HANDLE)h; if (tcdrain(dl0d->fd)) { fprintf(stderr, FLFMT "tcdrain returned %s.\n", FL, strerror(errno)); return diag_iseterr(DIAG_ERR_GENERAL); } SetCommBreak(hd); diag_os_millisleep(ms); ClearCommBreak(hd); return 0; }
int serialPort::portMode(setType setting, char *set) { switch (setting) { case CONFIG: strcpy(config, set); break; case EOSMODE: eosMode = *set; break; case CLEAR: #ifdef __WIN32__ SetCommBreak( handle ); Sleep ( 300 ); // sleep 300 ms ClearCommBreak( handle ); Sleep ( 50 ); // sleep 50 ms #endif #ifdef __linux__ printf("serialPort::portMode break 300\n"); tcsendbreak( handle, 300); // should send 300 ms break usleep(100000); // a bit of a guard after tcdrain( handle ); #endif break; case TIMEOUT: timeout = strtoul(set, NULL, 10) * 1000L; break; case PACING: pace = strtoul(set, NULL, 10) * 1000L; break; } return 0; }
// diag_tty_break #1 : use Set / ClearCommBreak // and return as soon as break is cleared. // ret 0 if ok int diag_tty_break(struct diag_l0_device *dl0d, const unsigned int ms) { LARGE_INTEGER qpc1, qpc2; //for timing verification long real_t; //"real" duration struct tty_int *wti = (struct tty_int *)dl0d->tty_int; int errval=0; if (wti->fd == INVALID_HANDLE_VALUE) { fprintf(stderr, FLFMT "Error. Is the port open ?\n", FL); return diag_iseterr(DIAG_ERR_GENERAL); } if (ms <= 1) return diag_iseterr(DIAG_ERR_GENERAL); QueryPerformanceCounter(&qpc1); errval = !SetCommBreak(wti->fd); QueryPerformanceCounter(&qpc2); //that call can take quite a while (6ms !!) on some setups (win7 + CH340 USB-Serial). //It's still impossible to know (from here) when exactly TXD goes low (beginning or end of the call) real_t=(long) (pf_conv * (qpc2.QuadPart-qpc1.QuadPart)) / 1000L; real_t = (long) ms - real_t; //time remaining if (real_t <= 0) real_t = 0; diag_os_millisleep((unsigned int ) real_t); errval |= !ClearCommBreak(wti->fd); if (errval) { //if either of the calls failed fprintf(stderr, FLFMT "tty_break could not set/clear break!\n", FL); return diag_iseterr(DIAG_ERR_GENERAL); } return 0; }
int RS232Interface::SetSerialBreak(int state) { int result = E2ERR_OPENFAILED; #ifdef _WINDOWS if (hCom != INVALID_HANDLE_VALUE) { if (state) SetCommBreak(hCom); else ClearCommBreak(hCom); result = OK; } #else #ifdef _LINUX_ #if defined(TIOCSBRK) && defined(TIOCCBRK) //check if available for compilation if (state) result = ioctl(fd,TIOCSBRK,0); else result = ioctl(fd,TIOCCBRK,0); #else UserDebug(UserApp1, "RS232Interface::SetSerialBreak Can't get IOCTL\n"); #endif #endif #endif return result; }
int xbee_ser_break( xbee_serial_t *serial, int enabled) { BOOL success; XBEE_SER_CHECK( serial); if (enabled) { success = SetCommBreak( serial->hCom); } else { success = ClearCommBreak( serial->hCom); } #ifdef XBEE_SERIAL_VERBOSE if (success == 0) { printf( "%s: {Set|Clear}CommBreak error %lu\n", __FUNCTION__, GetLastError()); } #endif return success ? 0 : -EIO; }
int serialCommunicator::SerialBreak() { #if defined WIN32 // Asio library doesn't support serial breaks on windows, so use win api boost::asio::deadline_timer timer(IO_service); // Set serial break SetCommBreak(newSerial->native_handle()); // Wait for defined period timer.expires_from_now(boost::posix_time::milliseconds(serialBreakms)); timer.wait(); // Blocks till the timer expires // Clear serial break ClearCommBreak(newSerial->native_handle()); #else // Otherwise send using the asio interface -NOTE this hasn't been tested yet. newSerial->send_break(); #endif return 1; }
int far pascal zClearCommBreak( int pp1 ) { int r; SaveRegs(); /* ** Log IN Parameters (No Create/Destroy Checking Yet!) */ LogIn( (LPSTR)"APICALL:ClearCommBreak int+", pp1 ); /* ** Call the API! */ RestoreRegs(); GrovelDS(); r = ClearCommBreak(pp1); UnGrovelDS(); SaveRegs(); /* ** Log Return Code & OUT Parameters (No Create/Destroy Checking Yet!) */ LogOut( (LPSTR)"APIRET:ClearCommBreak int++", r, (short)0 ); RestoreRegs(); return( r ); }
void com_break(int on) { COMMHANDLE h=ComGetHandle(hcModem); if (on) SetCommBreak(h); else ClearCommBreak(h); }
//уст. в указ. знач. линию TXD // bool CComPort::SetTXD(bool state) { //TODO: maybe use of EscapeCommFunction() will be more suitable? if (state) return SetCommBreak(m_hCom); else return ClearCommBreak(m_hCom); }
void SerialPort::sendBreak() { #ifdef __WIN32__ SetCommBreak(handle); ClearCommBreak(handle); #endif #if defined(__gnu_linux__) || (defined(__APPLE__) && defined(__MACH__)) tcsendbreak(handle, 0); #endif }
int wxSerialPort::SendBreak(int duration) { if(duration <= 0) duration = 1; if(!SetCommBreak(fd)) return -1; // win32 Sleep parameter is ms Sleep(duration * 250); if(!ClearCommBreak(fd)) return -1; // no error return 0; };
void CSerialPort::ClearBreak() { ASSERT(IsOpen()); if (!ClearCommBreak(m_hComm)) { TRACE(_T("Failed in call to SetCommBreak\n")); AfxThrowSerialException(); } }
static void serbreak_timer(void *ctx, long now) { Serial serial = (Serial)ctx; if (now >= serial->clearbreak_time && serial->port) { ClearCommBreak(serial->port); serial->break_in_progress = FALSE; logevent(serial->frontend, "Finished serial break"); } }
static void serbreak_timer(void *ctx, unsigned long now) { Serial *serial = (Serial *)ctx; if (now == serial->clearbreak_time && serial->port) { ClearCommBreak(serial->port); serial->break_in_progress = false; logevent(serial->logctx, "Finished serial break"); } }
// Transmit a continuous stream of zero bits for the given duration. If the // argument is 0, the transmission will last between 0.25 and 0.5 seconds. // Otherwise, the duration specfies the number of seconds to send the zero bit // stream. void SerialPortImplWin32::sendBreak(const vpr::Int32 duration) { DWORD flags; //Send a break for .5 seconds SetCommBreak(mHandle); Sleep(500); ClearCommBreak(mHandle); Sleep(35); ClearCommError(mHandle,&flags,NULL); //Clear the break error }
void serial_raw::set_break(int mode) { BX_DEBUG (("set break %s", mode?"on":"off")); #ifdef WIN32 if (mode) { SetCommBreak(hCOM); } else { ClearCommBreak(hCOM); } #endif }
/*----------------------------------------------------------------------------*/ int serial_read(int fd, void *buffer, unsigned size, unsigned timeout) { HANDLE h; COMMTIMEOUTS ct; int received = 0; h = get_h(fd); if(!h) return 0; if(!GetCommTimeouts(h,&ct)) { err_trace(__FILE__, __LINE__); return 0; } ct.ReadIntervalTimeout = MAXDWORD; ct.ReadTotalTimeoutMultiplier = MAXDWORD; ct.ReadTotalTimeoutConstant = timeout; if(!SetCommTimeouts(h,&ct)) { err_trace(__FILE__, __LINE__); return 0; } if(!ReadFile(h, buffer, size, (DWORD *)&received, NULL)) { DWORD Err; err_trace(__FILE__, __LINE__); ClearCommBreak(h); ClearCommError(h, &Err, NULL); return 0; } #ifdef DEBUG if(!received) { // err_trace(__FILE__, __LINE__); // TRACE("%s:%d: Timeout reached. Timeout: %u\n", __FILE__, __LINE__, timeout ); } else { int i; fprintf(stderr, "rx: "); for(i = 0; i < received; i++) fprintf(stderr, "%02x ", (unsigned)((char *)buffer)[i] & 0xff); fprintf(stderr, "\n"); } #endif return received; }
int ndiSerialBreak(HANDLE serial_port) { DWORD dumb; ClearCommError(serial_port,&dumb,NULL); /* clear error */ PurgeComm(serial_port,PURGE_TXCLEAR|PURGE_RXCLEAR); /* clear buffers */ SetCommBreak(serial_port); Sleep(300); /* hold break for 0.3 seconds */ ClearCommBreak(serial_port); return 0; }
/*------------------------------------------- | Name:startAsyncRs232 | Description: | Parameters: | Return Type: | Comments: | See: ---------------------------------------------*/ int startAsyncRs232(void) { uart_config config={DFLT_SPEED,DFLT_PARITY,DFLT_DATA,DFLT_STOPBIT}; hRS232PhysicalSimEvent=CreateEvent(NULL,FALSE,FALSE,NULL); hCom = CreateFile(USE_COM, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL ); if(hCom==INVALID_HANDLE_VALUE) return -1; //set comm setRs232(&config); // purge any information in the buffer PurgeComm( hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ); // ClearCommBreak(hCom); // //EscapeCommFunction( hCom, SETDTR ) ; // get any early notifications SetCommMask(hCom, EV_RXFLAG|EV_RXCHAR|EV_TXEMPTY); // setup device buffers SetupComm( hCom, 4096, 4096 ); // bComStopped=COM_START; hComThread = CreateThread( (LPSECURITY_ATTRIBUTES) NULL, 0, (LPTHREAD_START_ROUTINE) comThread, NULL, 0, &dwThreadID ); if(hComThread== INVALID_HANDLE_VALUE) return -1; printf("uart started\n"); return 0; }
//------------------------------------------------------------------- // Description: // Send a break on the com port for "len" msec // // portnum - number 0 to MAX_PORTNUM-1. This number is provided to // indicate the symbolic port number. // void BreakCOM(int portnum) { // start the reset pulse SetCommBreak(ComID[portnum]); // delay msDelay(2); // clear the reset pulse and return // PROGRAMMER'S NOTE: ClearCommBreak is returning 24:an undefined code ClearCommBreak(ComID[portnum]); // Win3.1 bug, close and then open port CloseCOM(portnum); OpenCOM(portnum,&port[0]); }
static int ser_windows_send_break (struct serial *scb) { HANDLE h = (HANDLE) _get_osfhandle (scb->fd); if (SetCommBreak (h) == 0) return -1; /* Delay for 250 milliseconds. */ Sleep (250); if (ClearCommBreak (h)) return -1; return 0; }
/***************************************************************** Routine: SerialBreak() Inputs: None. Returns: int COMM_OK if successful Description: This routine resets the COM PORT by sending a Serial Break to it. *****************************************************************/ int Comm32Port::SerialBreak() { if( m_hCommPort == INVALID_HANDLE_VALUE ) return COMM_NOT_INITIALIZED; if (!SetCommBreak( m_hCommPort )) return COMM_ERROR_SETBREAK; Sleep( m_ulSerBreakDelay ); if (!ClearCommBreak( m_hCommPort )) return COMM_ERROR_CLEARBREAK; return COMM_OK; } /* SerialBreak */
static void serial_terminate(Serial *serial) { if (serial->out) { handle_free(serial->out); serial->out = NULL; } if (serial->in) { handle_free(serial->in); serial->in = NULL; } if (serial->port != INVALID_HANDLE_VALUE) { if (serial->break_in_progress) ClearCommBreak(serial->port); CloseHandle(serial->port); serial->port = INVALID_HANDLE_VALUE; } }
// diag_tty_break #1 : use Set / ClearCommBreak // and return as soon as break is cleared. // ret 0 if ok int diag_tty_break(struct diag_l0_device *dl0d, const unsigned int ms) { LARGE_INTEGER qpc1, qpc2; //for timing verification static long correction=0; //running average offset (us) to add to the timeout long real_t; //"real" duration measured in us struct tty_int *wti = (struct tty_int *)dl0d->tty_int; int errval=0; if (wti->fd == INVALID_HANDLE_VALUE) { fprintf(stderr, FLFMT "Error. Is the port open ?\n", FL); return diag_iseterr(DIAG_ERR_GENERAL); } if ( (ms + correction/1000)<1) return diag_iseterr(DIAG_ERR_GENERAL); QueryPerformanceCounter(&qpc1); errval=!SetCommBreak(wti->fd); diag_os_millisleep(ms + correction/1000); QueryPerformanceCounter(&qpc2); errval += !ClearCommBreak(wti->fd); if (errval) { //if either of the calls failed fprintf(stderr, FLFMT "tty_break could not set/clear break!\n", FL); return diag_iseterr(DIAG_ERR_GENERAL); } real_t=(long) (pf_conv * (qpc2.QuadPart-qpc1.QuadPart)); //now verify if it's within 1ms of the requested delay. real_t = real_t - (ms*1000); if (real_t < -3000) { diag_os_millisleep((unsigned int)(real_t / -1000)); } else if ((real_t > -1000) && (real_t < 1000)) { //good enough: return 0; } //we're here if we were off by more than -3ms or +1ms. //correct by a fraction of the error. //diag_os_millisleep also does some self-correcting; we don't want to overdo it. correction = correction - (real_t / 3); //fprintf(stderr, FLFMT "tty_break off by %ldus, new correction=%ldus.\n", // FL, real_t, correction); return 0; }
/*================================================================= * Function ID : Close * Input : void * Output : void * Author : * Date : 2006 2 * Return : TRUE/FALSE * Description : 关闭串口 * Notice : * : * *=================================================================*/ void CComSmart::Close() { if( m_ReadOver.hEvent != NULL ) { CloseHandle(m_ReadOver.hEvent); m_ReadOver.hEvent = NULL ; } if( m_WriteOver.hEvent != NULL ) { CloseHandle(m_WriteOver.hEvent); m_WriteOver.hEvent = NULL ; } if( m_handle != INVALID_HANDLE_VALUE ) { ClearError(); ClearCommBreak(m_handle); CloseHandle(m_handle); m_handle = INVALID_HANDLE_VALUE; } m_IpPar.bConnect = false ; }
JNIEXPORT void JNICALL Java_gurux_io_NativeCode_setBreakState(JNIEnv* env, jclass clazz, jlong hComPort, jboolean value) { #if defined(_WIN32) || defined(_WIN64) if (value) { if (!SetCommBreak((HANDLE) hComPort)) { ReportError(env, GetLastError()); } } else { if (!ClearCommBreak((HANDLE) hComPort)) { ReportError(env, GetLastError()); } } #else int status = 0; if (value) { int ret = ioctl(hComPort, TIOCSBRK, &status); if (ret < 0) { ReportError(env, "setBreakState failed."); } } else { int ret = ioctl(hComPort, TIOCCBRK, &status); if (ret < 0) { ReportError(env, "setBreakState failed."); } } #endif }
void CommSendBreak(PComVar cv, int msec) /* for only serial ports */ { MSG DummyMsg; if ( ! cv->Ready ) { return; } switch (cv->PortType) { case IdSerial: /* Set com port into a break state */ SetCommBreak(cv->ComID); /* pause for 1 sec */ if (SetTimer(cv->HWin, IdBreakTimer, msec, NULL) != 0) { GetMessage(&DummyMsg,cv->HWin,WM_TIMER,WM_TIMER); } /* Set com port into the nonbreak state */ ClearCommBreak(cv->ComID); break; } }
void CSerialPort::check_error() { DWORD len; COMSTAT stat; char errStr[256]; if(INVALID_HANDLE_VALUE == m_hFile){ SetLastError(ERROR_INVALID_HANDLE); return; } memset(&stat, 0, sizeof(stat)); if( !ClearCommError(m_hFile, (LPDWORD)&len, &stat) ){ utils_trace( "Err in ClearCommError, code %d\n", GetLastError() ); return; } ClearCommBreak(m_hFile); if(!len){ return; } errStr[0] = 0; #define chk(e) \ do{if(len & e) {\ strcat(errStr, #e); \ strcat(errStr, " ");\ }}while(0) chk(CE_BREAK); chk(CE_DNS); chk(CE_FRAME); chk(CE_IOE); chk(CE_MODE); chk(CE_OOP); chk(CE_OVERRUN); chk(CE_PTO); chk(CE_RXOVER); chk(CE_RXPARITY); chk(CE_TXFULL); utils_trace( "Err 0x%08x(%s) on COM%d, COMSTAT=(0x%08x, 0x%08x, 0x%08x)\n", len, errStr, m_iPortNo, *((DWORD*)&stat), stat.cbInQue, stat.cbOutQue ); if(len & CE_RXOVER){ PurgeComm(m_hFile, PURGE_RXCLEAR | PURGE_RXABORT); } if(len & CE_TXFULL){ PurgeComm(m_hFile, PURGE_TXCLEAR | PURGE_TXABORT); } }
CDirectSerial::CDirectSerial (Bitu id, CommandLine* cmd) :CSerial (id, cmd) { InstallationSuccessful = false; hCom = INVALID_HANDLE_VALUE; // else destructor may close an invalid handle rx_retry = 0; rx_retry_max = 0; // open the port in NT object space (recommended by Microsoft) // allows the user to open COM10+ and custom port names. std::string prefix="\\\\.\\"; std::string tmpstring; if(!cmd->FindStringBegin("realport:",tmpstring,false)) return; #if SERIAL_DEBUG if(dbg_modemcontrol) fprintf(debugfp,"%12.3f Port type directserial realport %s\r\n", PIC_FullIndex(),tmpstring.c_str()); #endif prefix.append(tmpstring); // rxdelay: How many milliseconds to wait before causing an // overflow when the application is unresponsive. if(getBituSubstring("rxdelay:", &rx_retry_max, cmd)) { if(!(rx_retry_max<=10000)) { rx_retry_max=0; } } const char* tmpchar=prefix.c_str(); LOG_MSG ("Serial%d: Opening %s", COMNUMBER, tmpstring.c_str()); hCom = CreateFile (tmpchar, GENERIC_READ | GENERIC_WRITE, 0, // must be opened with exclusive-access NULL, // no security attributes OPEN_EXISTING, // must use OPEN_EXISTING 0, // non overlapped I/O NULL // hTemplate must be NULL for comm devices ); if (hCom == INVALID_HANDLE_VALUE) { int error = GetLastError (); LOG_MSG ("Serial%d: Serial Port \"%s\" could not be opened.", COMNUMBER, tmpstring.c_str()); if (error == 2) { LOG_MSG ("The specified port does not exist."); } else if (error == 5) { LOG_MSG ("The specified port is already in use."); } else { LOG_MSG ("Windows error %d occurred.", error); } return; } dcb.DCBlength=sizeof(dcb); fSuccess = GetCommState (hCom, &dcb); if (!fSuccess) { // Handle the error. LOG_MSG ("GetCommState failed with error %d.\n", (int)GetLastError ()); hCom = INVALID_HANDLE_VALUE; return; } // initialize the port dcb.BaudRate=CBR_9600; dcb.fBinary=true; dcb.fParity=true; dcb.fOutxCtsFlow=false; dcb.fOutxDsrFlow=false; dcb.fDtrControl=DTR_CONTROL_DISABLE; dcb.fDsrSensitivity=false; dcb.fOutX=false; dcb.fInX=false; dcb.fErrorChar=0; dcb.fNull=false; dcb.fRtsControl=RTS_CONTROL_DISABLE; dcb.fAbortOnError=false; dcb.ByteSize=8; dcb.Parity=NOPARITY; dcb.StopBits=ONESTOPBIT; fSuccess = SetCommState (hCom, &dcb); if (!fSuccess) { // Handle the error. LOG_MSG ("SetCommState failed with error %d.\n", (int)GetLastError ()); hCom = INVALID_HANDLE_VALUE; return; } // Configure timeouts to effectively use polling COMMTIMEOUTS ct; ct.ReadIntervalTimeout = MAXDWORD; ct.ReadTotalTimeoutConstant = 0; ct.ReadTotalTimeoutMultiplier = 0; ct.WriteTotalTimeoutConstant = 0; ct.WriteTotalTimeoutMultiplier = 0; SetCommTimeouts (hCom, &ct); CSerial::Init_Registers(); InstallationSuccessful = true; receiveblock=false; ClearCommBreak (hCom); setEvent(SERIAL_POLLING_EVENT, 1); // millisecond tick }
void CDirectSerial::setBreak (bool value) { if (value) SetCommBreak (hCom); else ClearCommBreak (hCom); }