int RS232Interface::SetSerialRTSDTR(int state) { int result = E2ERR_OPENFAILED; #ifdef _WINDOWS if ( hCom != INVALID_HANDLE_VALUE ) { if (state) { EscapeCommFunction(hCom, SETRTS); EscapeCommFunction(hCom, SETDTR); } else { EscapeCommFunction(hCom, CLRRTS); EscapeCommFunction(hCom, CLRDTR); } result = OK; } #else #ifdef _LINUX_ int flags; ioctl(fd,TIOCMGET, &flags); if (state) { flags |= (TIOCM_RTS|TIOCM_DTR); } else { flags &= ~(TIOCM_RTS|TIOCM_DTR); } result = ioctl(fd,TIOCMSET, &flags); #endif #endif return result; }
void CSerialPort::Close() { if (m_hTTY != INVALID_HANDLE_VALUE) { // disable event notification and wait for thread to halt SetCommMask( m_hTTY, 0 ); // drop DTR EscapeCommFunction( m_hTTY, CLRDTR); // SETRTS // purge reads/writes PurgeComm( m_hTTY, PURGE_TXABORT | PURGE_RXABORT); CloseHandle( m_hTTY ); m_hTTY = INVALID_HANDLE_VALUE; } }
VALUE setRtsIO(VALUE self, VALUE rb_int) { { Check_Type(rb_int, T_FIXNUM); } int boolean = FIX2INT(rb_int); PortDescriptor *port = NULL; Data_Get_Struct(self, PortDescriptor, port); return INT2FIX( EscapeCommFunction(port->fd, boolean == 1 ? SETRTS : CLRRTS) ); }
/* * Open the given com port and reset the attached cm17a */ int Cm17aStart(int comPortNumber) { char comPortString[80] ; sprintf(comPortString, "\\\\.\\COM%d", comPortNumber) ; thePort = CreateFile(comPortString, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL) ; if (thePort != INVALID_HANDLE_VALUE) { /* Reset the device */ EscapeCommFunction(thePort, CLRDTR) ; EscapeCommFunction(thePort, CLRRTS) ; Sleep(DELAY) ; EscapeCommFunction(thePort, SETDTR) ; EscapeCommFunction(thePort, SETRTS) ; Sleep(DELAY) ; return 1 ; } else return 0 ; }
void SerialPort::clearRTS() { if (!isOpen()) return; #ifdef __WIN32__ EscapeCommFunction(handle, CLRRTS); #endif #ifdef __gnu_linux__ int bit = TIOCM_RTS; ioctl(handle, TIOCMBIC, &bit); #endif #if defined(__APPLE__) && defined(__MACH__) ioctl(handle, TIOCM_RTS); #endif }
void SerialPort::setDTR() { if (!isOpen()) return; #ifdef __WIN32__ EscapeCommFunction(handle, SETDTR); #endif #ifdef __gnu_linux__ int bit = TIOCM_DTR; ioctl(handle, TIOCMBIS, &bit); #endif #if defined(__APPLE__) && defined(__MACH__) ioctl(handle, TIOCSDTR); #endif }
int XTTY::Connect(BOOL fConnect) { if (fConnect) { // オンラインにする if (m_fConnect) // 既にオンライン? return 0; // 何もせずに終わる m_idComDev = OpenComm("COM2", 1024, 128); if (m_idComDev < 0) { // オープンに失敗? OpenComm_Error(m_idComDev); return -1; } DCB dcb; GetCommState(m_idComDev, &dcb); dcb.BaudRate = 57600; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; SetCommState(&dcb); GetCommState(m_idComDev, &dcb); EnableCommNotification(m_idComDev, m_hwnd, 80, -1); EscapeCommFunction(m_idComDev, SETDTR); m_fConnect = TRUE; } else { // オフラインにする if (!m_fConnect) // 既にオフライン? return 0; // 何もせずに終わる EscapeCommFunction(m_idComDev, CLRDTR); CloseComm(m_idComDev); m_fConnect = FALSE; } return 0; }
void os_com_close() { // reset error byte if (!EscapeCommFunction((HANDLE) hSerial, CLRDTR)) { } if (!PurgeComm((HANDLE) hSerial, PURGE_RXABORT | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_TXCLEAR)) { } // device handle CloseHandle((HANDLE) hSerial); }
static int gry_probe(CableHandle *h) { DWORD status; //MS_CTS_ON or MS_DTR_ON EscapeCommFunction(hCom, SETDTR); EscapeCommFunction(hCom, SETRTS); GetCommModemStatus(hCom, &status); // Get MCR values if (status != 0x20) return ERR_PROBE_FAILED; EscapeCommFunction(hCom, SETDTR); EscapeCommFunction(hCom, CLRRTS); GetCommModemStatus(hCom, &status); if (status != 0x20) return ERR_PROBE_FAILED; EscapeCommFunction(hCom, CLRDTR); EscapeCommFunction(hCom, CLRRTS); GetCommModemStatus(hCom, &status); if (status != 0x00) return ERR_PROBE_FAILED; EscapeCommFunction(hCom, CLRDTR); EscapeCommFunction(hCom, SETRTS); GetCommModemStatus(hCom, &status); if (status != 0x00) return ERR_PROBE_FAILED; EscapeCommFunction(hCom, SETDTR); EscapeCommFunction(hCom, SETRTS); GetCommModemStatus(hCom, &status); if (status != 0x20) return ERR_PROBE_FAILED; return 0; }
//--------------------------------------------------------------------------- // Closes the connection to the port. // // 'portnum' - number 0 to MAX_PORTNUM-1. This number was provided to // OpenCOM to indicate the port number. // void CloseCOM(int portnum) { // disable event notification and wait for thread // to halt SetCommMask(ComID[portnum], 0); // drop DTR EscapeCommFunction(ComID[portnum], CLRDTR); // purge any outstanding reads/writes and close device handle PurgeComm(ComID[portnum], PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ); CloseHandle(ComID[portnum]); ComID[portnum] = 0; }
BOOL SerialCommunicationThread::CloseSerialPort(void) { if (COMFile != NULL) { //禁止串行端口所有事件 SetCommMask(COMFile, 0); //清除数据终端就绪信号 EscapeCommFunction(COMFile, CLRDTR); //丢弃通信资源的输出或输入缓冲区字符并终止在通信资源上挂起的读、写操操作 PurgeComm(COMFile, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); CloseHandle(COMFile); } COMFile = NULL; return TRUE; }
BOOL COM_Signal( int item, DWORD signal ) { BOOL ok=TRUE; if( !EscapeCommFunction(COM_Item[item].comH,signal) ) { COM_errorf("COM_Signal(COM%d,%s) EscapeCommFunction() Failed (%s).\n",COM_Item[item].comX,STR_TextCode(COM_SignalText,signal),COM_Error()); ok = FALSE; } else { COM_debugf("COM_Signal(COM%d,%s) OK.\n",COM_Item[item].comX,STR_TextCode(COM_SignalText,signal)); } return(ok); }
/*! * Defines our serial DTR and RTS pins states. * \param[in] handle Our serial communication handle. * \param[in] function One of the SbgEscapeComm enum function. * \return SBG_NO_ERROR if the pin state has been defined. */ SbgErrorCode sbgSetEscapeComm(SbgDeviceHandle handle, SbgEscapeComm function) { HANDLE pSerialDevice = (HANDLE)handle; uint32 escapeCommFunction; // // Check if we have a valid serial connexion // if (handle != SBG_INVALID_DEVICE_HANDLE) { // // Translate our sbgCom espace function into our windows one // switch (function) { case SBG_SET_DTR: escapeCommFunction = SETDTR; break; case SBG_CLR_DTR: escapeCommFunction = CLRDTR; break; case SBG_SET_RTS: escapeCommFunction = SETRTS; break; case SBG_CLR_RTS: default: escapeCommFunction = CLRRTS; break; } // // Define our espace comm function // if (EscapeCommFunction(pSerialDevice, escapeCommFunction)) { return SBG_NO_ERROR; } else { return SBG_ERROR; } } else { return SBG_NULL_POINTER; } }
char closeserial(portstream_fd portstream) { if (portstream != NULL) { // disable event notification SetCommMask( portstream, 0 ) ; // drop DTR EscapeCommFunction( portstream, CLRDTR ) ; // purge any outstanding reads/writes and close device handle PurgeComm( portstream, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ); // close the device err = CloseHandle( portstream ) ; portstream = (HANDLE) -1; if (err < 0) return -1; } return 0; }
void Serial_Port::close_serial() { printf("CLOSE SERIAL PORT\n"); // Enable all events in serial port FALSE SetCommMask(hComm, 0) ; EscapeCommFunction( hComm, CLRDTR ) ; PurgeComm( hComm, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ) ; CloseHandle( hComm ); hComm = NULL; status = false; printf("\n"); }
static BOOL CloseConnection(LPCOMMINFO hCom) { if (NULL == hCom) return (FALSE); // drop DTR EscapeCommFunction(hCom->hComPort, CLRDTR); // purge any outstanding reads/writes and close device handle PurgeComm(hCom->hComPort, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); // close handle CloseHandle(hCom->hComPort); return (TRUE); } // end of CloseConnection()
int wxSerialPort::ChangeLineState(wxSerialLineState flags) { #if ( 1 ) BOOL ok = false; if(flags & wxSERIAL_LINESTATE_DTR) { if(m_rtsdtr_state & wxSERIAL_LINESTATE_DTR) { ok = EscapeCommFunction(fd,CLRDTR); } else { ok = EscapeCommFunction(fd,SETDTR); } m_rtsdtr_state ^= wxSERIAL_LINESTATE_DTR; } if(flags & wxSERIAL_LINESTATE_RTS) { if(m_rtsdtr_state & wxSERIAL_LINESTATE_RTS) { ok = EscapeCommFunction(fd,CLRRTS); } else { ok = EscapeCommFunction(fd,SETRTS); } m_rtsdtr_state ^= wxSERIAL_LINESTATE_RTS; } if(!ok) return -1; return 0; #else BOOL ok = false; if(flags & wxSERIAL_LINESTATE_DTR) ok = EscapeCommFunction(fd,SETDTR); else ok = EscapeCommFunction(fd,CLRDTR); if(flags & wxSERIAL_LINESTATE_RTS) ok = EscapeCommFunction(fd,SETRTS); else ok = EscapeCommFunction(fd,CLRRTS); if(!ok) return -1; return 0; #endif };
int xbee_ser_set_rts( xbee_serial_t *serial, int asserted) { BOOL success; XBEE_SER_CHECK( serial); // disable flow control so our manual setting will stick xbee_ser_flowcontrol( serial, 0); success = EscapeCommFunction( serial->hCom, asserted ? SETRTS : CLRRTS); #ifdef XBEE_SERIAL_VERBOSE if (success == 0) { printf( "%s: EscapeCommFunction error %lu\n", __FUNCTION__, GetLastError()); } #endif return success ? 0 : -EIO; }
// 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; }
JNIEXPORT void JNICALL Java_gurux_io_NativeCode_setRtsEnable(JNIEnv* env, jclass clazz, jlong hComPort, jboolean value) { #if defined(_WIN32) || defined(_WIN64) DWORD tmp; if (value) { tmp = SETRTS; } else { tmp = CLRRTS; } if (EscapeCommFunction((HANDLE) hComPort, tmp) == 0) { ReportError(env, GetLastError()); } #else int status = 0; int ret = ioctl(hComPort, TIOCMGET, &status); if (ret != 0) { ReportError(env, "setRtsEnable failed."); } if (value) { status |= TIOCM_RTS; } else { status &= ~TIOCM_RTS; } ret = ioctl(hComPort, TIOCMSET, &status); if (ret != 0) { ReportError(env, "setRtsEnable failed."); } #endif }
// Disconnects port void commDisconnect() { // disconnects with serial port if connected HMENU hMenu; // Check if we're connected if (CONNECTED(TTYInfo)) { // Menu hMenu = GetMenu(ghWndMain); // get the menu handle EnableMenuItem(hMenu, ID_FILE_CONNECT, MF_ENABLED); // enable the connect menu EnableMenuItem(hMenu, ID_FILE_DISCONNECT, MF_GRAYED | MF_DISABLED); // disable the connect menu EnableMenuItem(hMenu, ID_EDIT_SETTINGS, MF_ENABLED); // enable the TTY menu // lower DTR EscapeCommFunction(COMDEV(TTYInfo), CLRDTR); // Purge reads/writes, and I/O buffer PurgeComm(COMDEV(TTYInfo), PURGE_FLAGS); CloseHandle(COMDEV(TTYInfo)); // release the handle TTYInfo.fThreadDone = TRUE; // we want the thread to end CONNECTED(TTYInfo) = FALSE; // we are now disconnected } }
////////////////////////////////////////////////////////////////////// // CloseConnection // return: 0 always // int CAsyncPort::CloseConnection() { // not connected m_isConnected = FALSE; // disable event notification and wait for thread to halt SetCommMask(m_hCommDev, 0); // block until thread has been halted while (m_dwThreadID != 0) { Sleep(10); } // drop DTR EscapeCommFunction(m_hCommDev, CLRDTR); // purge any outstanding reads/writes and close device handle PurgeComm ( m_hCommDev, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR ); // close device CloseHandle(m_hCommDev); // reset instance variables m_hCommDev = INVALID_HANDLE_VALUE; memset(m_szCommDevName, 0, sizeof (m_szCommDevName)); memset(& m_commConfig, 0, sizeof (COMMCONFIG));; m_commConfig.dwSize = sizeof (COMMCONFIG); memset(& m_commProp, 0, sizeof (COMMPROP)); memset(& m_commTimeOuts, 0, sizeof (COMMTIMEOUTS)); memset(m_baInBuf, 0, sizeof (m_baInBuf)); m_nInBufIndex = 0; m_nInBufSize = 0; return (0); }
bool SerialPort::openPort(const char *device, int baudrate, bool bXonXoff, int DTRtime) { close(); d->m_time = DTRtime; d->m_baudrate = baudrate; d->m_bXonXoff = bXonXoff; string port; // = "\\\\.\\"; port += device; port += ":"; d->hPort = CreateFileA(port.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); if (d->hPort == INVALID_HANDLE_VALUE){ close(); log(L_WARN, "Can' open %s", port.c_str()); return false; } FlushFileBuffers(d->hPort); if (!EscapeCommFunction(d->hPort, CLRDTR)){ close(); log(L_WARN, "Clear DTR error"); return false; } d->m_timer->start(d->m_time, true); return true; }
void EIO_Set(uv_work_t* req) { SetBaton* data = static_cast<SetBaton*>(req->data); if (data->rts) { EscapeCommFunction((HANDLE)data->fd, SETRTS); } else { EscapeCommFunction((HANDLE)data->fd, CLRRTS); } if (data->dtr) { EscapeCommFunction((HANDLE)data->fd, SETDTR); } else { EscapeCommFunction((HANDLE)data->fd, CLRDTR); } if (data->brk) { EscapeCommFunction((HANDLE)data->fd, SETBREAK); } else { EscapeCommFunction((HANDLE)data->fd, CLRBREAK); } DWORD bits = 0; GetCommMask((HANDLE)data->fd, &bits); bits &= ~(EV_CTS | EV_DSR); if (data->cts) { bits |= EV_CTS; } if (data->dsr) { bits |= EV_DSR; } if (!SetCommMask((HANDLE)data->fd, bits)) { ErrorCodeToString("Setting options on COM port (SetCommMask)", GetLastError(), data->errorString); return; } }
void EIO_Set(uv_work_t* req) { SetBaton* data = static_cast<SetBaton*>(req->data); if (data->rts) { EscapeCommFunction((HANDLE)data->fd, SETRTS); } else { EscapeCommFunction((HANDLE)data->fd, CLRRTS); } if (data->dtr) { EscapeCommFunction((HANDLE)data->fd, SETDTR); } else { EscapeCommFunction((HANDLE)data->fd, CLRDTR); } if (data->brk) { EscapeCommFunction((HANDLE)data->fd, SETBREAK); } else { EscapeCommFunction((HANDLE)data->fd, CLRBREAK); } DWORD bits = 0; GetCommMask((HANDLE)data->fd, &bits); bits &= ~(EV_CTS | EV_DSR); if (data->cts) { bits |= EV_CTS; } if (data->dsr) { bits |= EV_DSR; } // TODO check for error data->result = SetCommMask((HANDLE)data->fd, bits); }
UsbSerial::UsbStatus UsbSerial::openDevice( TCHAR* deviceName ) { DCB dcb; COMMTIMEOUTS timeouts; // if it's already open, do nothing if( deviceOpen ) return ALREADY_OPEN; // Open the port deviceHandle = CreateFile( deviceName, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0 ); if ( deviceHandle == INVALID_HANDLE_VALUE ) return ERROR_CLOSE; // initialize the overlapped structures overlappedRead.Offset = overlappedWrite.Offset = 0; overlappedRead.OffsetHigh = overlappedWrite.OffsetHigh = 0; overlappedRead.hEvent = CreateEvent(0, TRUE, FALSE, 0); overlappedWrite.hEvent = CreateEvent(0, TRUE, FALSE, 0); if (!overlappedRead.hEvent || !overlappedWrite.hEvent ) { deviceHandle = INVALID_HANDLE_VALUE; return ERROR_CLOSE; } GetCommState( deviceHandle, &dcb ); dcb.BaudRate = CBR_115200; dcb.ByteSize = 8; dcb.Parity = NOPARITY; dcb.StopBits = ONESTOPBIT; dcb.fOutxCtsFlow = TRUE; dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; dcb.fAbortOnError = TRUE; dcb.fDtrControl = DTR_CONTROL_ENABLE; // magic testing... if( !SetCommState( deviceHandle, &dcb ) ) { deviceHandle = INVALID_HANDLE_VALUE; return ERROR_CLOSE; } /* From MSDN: 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: * If there are any bytes in the input buffer, ReadFile returns immediately with the bytes in the buffer. * If there are no bytes in the input buffer, ReadFile waits until a byte arrives and then returns immediately. * If no bytes arrive within the time specified by ReadTotalTimeoutConstant, ReadFile times out. */ timeouts.ReadIntervalTimeout = MAXDWORD; timeouts.ReadTotalTimeoutMultiplier = MAXDWORD; timeouts.ReadTotalTimeoutConstant = 500; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 0; if( ! SetCommTimeouts( deviceHandle, &timeouts ) ) { deviceHandle = INVALID_HANDLE_VALUE; return ERROR_CLOSE; } EscapeCommFunction( deviceHandle, SETDTR ); return OK; }
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; } }
// Open a port, by name. Return 0 on success, non-zero for error int Serial::Open(const wxString& name) { Close(); #if defined(LINUX) struct serial_struct kernel_serial_settings; int bits; port_fd = open(name.mb_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); if (port_fd < 0) { if (errno == EACCES) { error_msg = _("Unable to access ") + wxString(name,wxConvUTF8) + _(", insufficient permission"); // TODO: we could look at the permission bits and owner // to make a better message here } else if (errno == EISDIR) { error_msg = _("Unable to open ") + wxString(name,wxConvUTF8) + _(", Object is a directory, not a serial port"); } else if (errno == ENODEV || errno == ENXIO) { error_msg = _("Unable to open ") + wxString(name,wxConvUTF8) + _(", Serial port hardware not installed"); } else if (errno == ENOENT) { error_msg = _("Unable to open ") + wxString(name,wxConvUTF8) + _(", Device name does not exist"); } else { error_msg = _("Unable to open ") + wxString(name,wxConvUTF8) + _(", ") + wxString(strerror(errno),wxConvUTF8); } return -1; } if (ioctl(port_fd, TIOCMGET, &bits) < 0) { close(port_fd); error_msg = _("Unable to query serial port signals"); return -1; } bits &= ~(TIOCM_DTR | TIOCM_RTS); if (ioctl(port_fd, TIOCMSET, &bits) < 0) { close(port_fd); error_msg = _("Unable to control serial port signals"); return -1; } if (tcgetattr(port_fd, &settings_orig) != 0) { close(port_fd); error_msg = _("Unable to query serial port settings (perhaps not a serial port)"); return -1; } memset(&settings, 0, sizeof(settings)); settings.c_iflag = IGNBRK | IGNPAR; settings.c_cflag = CS8 | CREAD | HUPCL | CLOCAL; Set_baud(baud_rate); if (ioctl(port_fd, TIOCGSERIAL, &kernel_serial_settings) == 0) { kernel_serial_settings.flags |= ASYNC_LOW_LATENCY; ioctl(port_fd, TIOCSSERIAL, &kernel_serial_settings); } tcflush(port_fd, TCIFLUSH); #elif defined(MACOSX) int bits; port_fd = open(name.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); if (port_fd < 0) { error_msg = _("Unable to open ") + name + _(", ") + strerror(errno); return -1; } if (ioctl(port_fd, TIOCEXCL) == -1) { close(port_fd); error_msg = _("Unable to get exclussive access to port ") + name; return -1; } if (ioctl(port_fd, TIOCMGET, &bits) < 0) { close(port_fd); error_msg = _("Unable to query serial port signals on ") + name; return -1; } bits &= ~(TIOCM_DTR | TIOCM_RTS); if (ioctl(port_fd, TIOCMSET, &bits) < 0) { close(port_fd); error_msg = _("Unable to control serial port signals on ") + name; return -1; } if (tcgetattr(port_fd, &settings_orig) < 0) { close(port_fd); error_msg = _("Unable to access baud rate on port ") + name; return -1; } memset(&settings, 0, sizeof(settings)); settings.c_cflag = CS8 | CLOCAL | CREAD | HUPCL; settings.c_iflag = IGNBRK | IGNPAR; Set_baud(baud_rate); tcflush(port_fd, TCIFLUSH); #elif defined(WINDOWS) COMMCONFIG cfg; COMMTIMEOUTS timeouts; int got_default_cfg=0, port_num; char buf[1024], name_createfile[64], name_commconfig[64], *p; DWORD len; snprintf(buf, sizeof(buf), _("%s"), name.c_str()); p = strstr(buf, _("COM")); if (p && sscanf(p + 3, _("%d"), &port_num) == 1) { printf(_("port_num = %d\n"), port_num); snprintf(name_createfile, sizeof(name_createfile), _("\\\\.\\COM%d"), port_num); snprintf(name_commconfig, sizeof(name_commconfig), _("COM%d"), port_num); } else { snprintf(name_createfile, sizeof(name_createfile), _("%s"), name.c_str()); snprintf(name_commconfig, sizeof(name_commconfig), _("%s"), name.c_str()); } len = sizeof(COMMCONFIG); if (GetDefaultCommConfig(name_commconfig, &cfg, &len)) { // this prevents unintentionally raising DTR when opening // might only work on COM1 to COM9 got_default_cfg = 1; memcpy(&port_cfg_orig, &cfg, sizeof(COMMCONFIG)); cfg.dcb.fDtrControl = DTR_CONTROL_DISABLE; cfg.dcb.fRtsControl = RTS_CONTROL_DISABLE; SetDefaultCommConfig(name_commconfig, &cfg, sizeof(COMMCONFIG)); } else { printf(_("error with GetDefaultCommConfig\n")); } port_handle = CreateFile(name_createfile, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (port_handle == INVALID_HANDLE_VALUE) { win32_err(buf); error_msg = _("Unable to open ") + name + _(", ") + buf; return -1; } len = sizeof(COMMCONFIG); if (!GetCommConfig(port_handle, &port_cfg, &len)) { CloseHandle(port_handle); win32_err(buf); error_msg = _("Unable to read communication config on ") + name + _(", ") + buf; return -1; } if (!got_default_cfg) { memcpy(&port_cfg_orig, &port_cfg, sizeof(COMMCONFIG)); } // http://msdn2.microsoft.com/en-us/library/aa363188(VS.85).aspx port_cfg.dcb.BaudRate = baud_rate; port_cfg.dcb.fBinary = TRUE; port_cfg.dcb.fParity = FALSE; port_cfg.dcb.fOutxCtsFlow = FALSE; port_cfg.dcb.fOutxDsrFlow = FALSE; port_cfg.dcb.fDtrControl = DTR_CONTROL_DISABLE; port_cfg.dcb.fDsrSensitivity = FALSE; port_cfg.dcb.fTXContinueOnXoff = TRUE; // ??? port_cfg.dcb.fOutX = FALSE; port_cfg.dcb.fInX = FALSE; port_cfg.dcb.fErrorChar = FALSE; port_cfg.dcb.fNull = FALSE; port_cfg.dcb.fRtsControl = RTS_CONTROL_DISABLE; port_cfg.dcb.fAbortOnError = FALSE; port_cfg.dcb.ByteSize = 8; port_cfg.dcb.Parity = NOPARITY; port_cfg.dcb.StopBits = ONESTOPBIT; if (!SetCommConfig(port_handle, &port_cfg, sizeof(COMMCONFIG))) { CloseHandle(port_handle); win32_err(buf); error_msg = _("Unable to write communication config to ") + name + _(", ") + buf; return -1; } if (!EscapeCommFunction(port_handle, CLRDTR | CLRRTS)) { CloseHandle(port_handle); win32_err(buf); error_msg = _("Unable to control serial port signals on ") + name + _(", ") + buf; return -1; } // http://msdn2.microsoft.com/en-us/library/aa363190(VS.85).aspx // setting to all zeros means timeouts are not used //timeouts.ReadIntervalTimeout = 0; timeouts.ReadIntervalTimeout = MAXDWORD; timeouts.ReadTotalTimeoutMultiplier = 0; timeouts.ReadTotalTimeoutConstant = 0; timeouts.WriteTotalTimeoutMultiplier = 0; timeouts.WriteTotalTimeoutConstant = 0; if (!SetCommTimeouts(port_handle, &timeouts)) { CloseHandle(port_handle); win32_err(buf); error_msg = _("Unable to write timeout settings to ") + name + _(", ") + buf; return -1; } #endif port_name = name; port_is_open = 1; return 0; }
/*----------------------------------------------------------------------------- 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; } }
void RS232_disableRTS(int comport_number) { EscapeCommFunction(Cport[comport_number], CLRRTS); }