本文整理汇总了C++中SetCommTimeouts函数的典型用法代码示例。如果您正苦于以下问题:C++ SetCommTimeouts函数的具体用法?C++ SetCommTimeouts怎么用?C++ SetCommTimeouts使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SetCommTimeouts函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
int _CRTAPI1 main(int argc, char *argv[]) {
CHAR *myPort = "COM1";
DCB myDcb;
DWORD junk;
COMMTIMEOUTS myTimeOuts;
DWORD numberActuallyRead;
DWORD numberActuallyWritten;
UCHAR readBuff[1000];
HANDLE comHandle;
DWORD startingTicks;
OVERLAPPED readOl;
OVERLAPPED writeOl;
UCHAR writeBuff[5] = {0,1,2,3,4};
if (argc > 1) {
myPort = argv[1];
}
if ((comHandle = CreateFile(
myPort,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL
)) == ((HANDLE)-1)) {
FAILURE;
}
if (!(readOl.hEvent = CreateEvent(
NULL,
TRUE,
FALSE,
NULL
))) {
FAILURE;
}
if (!(writeOl.hEvent = CreateEvent(
NULL,
TRUE,
FALSE,
NULL
))) {
FAILURE;
}
if (!GetCommState(
comHandle,
&myDcb
)) {
FAILURE;
}
myDcb.BaudRate = 19200;
myDcb.ByteSize = 8;
myDcb.StopBits = ONESTOPBIT;
myDcb.Parity = NOPARITY;
myDcb.fOutxCtsFlow = FALSE;
myDcb.fOutxDsrFlow = FALSE;
myDcb.fDsrSensitivity = FALSE;
myDcb.fOutX = FALSE;
myDcb.fInX = FALSE;
myDcb.fRtsControl = RTS_CONTROL_ENABLE;
myDcb.fDtrControl = DTR_CONTROL_ENABLE;
if (!SetCommState(
comHandle,
&myDcb
)) {
FAILURE;
}
//
// Test to make sure that all maxdword on read is illegal.
//
myTimeOuts.ReadIntervalTimeout = MAXDWORD;
myTimeOuts.ReadTotalTimeoutMultiplier = MAXDWORD;
myTimeOuts.ReadTotalTimeoutConstant = MAXDWORD;
myTimeOuts.WriteTotalTimeoutMultiplier = MAXDWORD;
myTimeOuts.WriteTotalTimeoutConstant = MAXDWORD;
if (SetCommTimeouts(
comHandle,
&myTimeOuts
)) {
//.........这里部分代码省略.........
示例2: serial_open
//.........这里部分代码省略.........
tio.c_iflag = IGNPAR;
tio.c_oflag = 0;
tio.c_cc[VMIN] = 0;
tio.c_cc[VTIME] = 0;
// Attempt to set line speed for input & output
if(cfsetispeed(&tio, spd) != 0) {
print_linux_error();
return 0;
}
if(cfsetospeed(&tio, spd) != 0) {
print_linux_error();
return 0;
}
// Attempt to set configuration
if(tcsetattr(fd, TCSANOW, &tio) != 0) {
print_linux_error();
return 0;
}
#else
// Open windows serial port
HANDLE wsid = CreateFile(device,
GENERIC_READ|GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if(wsid == INVALID_HANDLE_VALUE) {
print_windows_error();
return 0;
}
// Get params
DCB dcbSerialParams = {0};
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
if (!GetCommState(wsid, &dcbSerialParams)) {
print_windows_error();
return 0;
}
// Set new params. Remember to disable flow control etc.
dcbSerialParams.ByteSize = 8;
dcbSerialParams.StopBits = ONESTOPBIT;
dcbSerialParams.Parity = NOPARITY;
dcbSerialParams.fOutxCtsFlow = FALSE;
dcbSerialParams.fOutxDsrFlow = FALSE;
dcbSerialParams.fRtsControl = RTS_CONTROL_DISABLE;
// Select speed
switch(speed) {
case SERIAL_1200: dcbSerialParams.BaudRate = CBR_1200; break;
case SERIAL_2400: dcbSerialParams.BaudRate = CBR_2400; break;
case SERIAL_4800: dcbSerialParams.BaudRate = CBR_4800; break;
case SERIAL_9600: dcbSerialParams.BaudRate = CBR_9600; break;
case SERIAL_14400: dcbSerialParams.BaudRate = CBR_14400; break;
case SERIAL_19200: dcbSerialParams.BaudRate = CBR_19200; break;
case SERIAL_38400: dcbSerialParams.BaudRate = CBR_38400; break;
case SERIAL_56000: dcbSerialParams.BaudRate = CBR_56000; break;
case SERIAL_57600: dcbSerialParams.BaudRate = CBR_57600; break;
case SERIAL_115200: dcbSerialParams.BaudRate = CBR_115200; break;
case SERIAL_128000: dcbSerialParams.BaudRate = CBR_128000; break;
case SERIAL_256000: dcbSerialParams.BaudRate = CBR_256000; break;
default:
sprintf(error_str, "Speed not supported!");
return 0;
}
// Set serial port settings
if(!SetCommState(wsid, &dcbSerialParams)) {
print_windows_error();
return 0;
}
// Set serial port timeouts
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 0;
// Set timeouts
if(!SetCommTimeouts(wsid, &timeouts)) {
print_windows_error();
return 0;
}
#endif
// Reserve serial port stuff
port = malloc(sizeof(serial_port));
#ifdef LINUX
port->handle = fd;
#else
port->handle = wsid;
#endif
port->ok = 1;
return port;
}
示例3: tr
// --- функция открытия порта --------------------------------------------------
HANDLE MainWindow::OpenPort(QString PortName)
{
HANDLE PortToOpen = CreateFileA
(
PortName.toAscii(), // имя порта
GENERIC_READ | GENERIC_WRITE, // можно читать и писать
0, // ни с кем портом не делиться
NULL, // потомкам хэндл не доступен
OPEN_EXISTING, // открыть существующий порт
FILE_ATTRIBUTE_NORMAL, // без атрибутов
0
);
if(PortToOpen==INVALID_HANDLE_VALUE)
{
logstr = tr("] <font color=red>не удалось открыть порт</font>");
string2log(logstr);
} else
{
logstr = "[";
currtime = currtime.currentTime();
logstr.append(currtime.toString());
logstr.append(tr("] порт <b>") + portstr + tr("</b> открыт"));
ui->log->append(logstr);
// очистка буферов порта
if(!PurgeComm(PortToOpen, PURGE_RXABORT | PURGE_TXABORT | PURGE_RXCLEAR | PURGE_TXCLEAR))
{
logstr = tr("] <font color=red>не удалось очистить буферы порта</font>");
string2log(logstr);
CloseHandle(PortToOpen);
return INVALID_HANDLE_VALUE;
} else {
logstr = tr("] буферы порта очищены");
string2log(logstr);
}
// настройка параметров порта
DCB dcb;
BOOL PortState;
dcb.DCBlength = sizeof(DCB);
PortState = GetCommState(PortToOpen,&dcb);
dcb.BaudRate=config->value("port/Baud_Rate", "2400").value<int>();
dcb.ByteSize=config->value("port/DataBits", "8").value<int>();
dcb.Parity=config->value("port/Parity", "0").value<int>();
dcb.StopBits=config->value("port/StopBits", "1").value<int>();
if(!SetCommState(PortToOpen,&dcb))
{
logstr = tr("] <font color=red>не удалось настроить порт</font>");
string2log(logstr);
CloseHandle(PortToOpen);
return INVALID_HANDLE_VALUE;
} else {
logstr = tr("] порт настроен");
string2log(logstr);
}
// установка таймаутов
COMMTIMEOUTS CommTimeOuts;
CommTimeOuts.ReadIntervalTimeout = 0xFFFFFFFF;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0;
CommTimeOuts.ReadTotalTimeoutConstant = TIMEOUT;
CommTimeOuts.WriteTotalTimeoutMultiplier = 0;
CommTimeOuts.WriteTotalTimeoutConstant = TIMEOUT;
if(!SetCommTimeouts(PortToOpen, &CommTimeOuts))
{
logstr = tr("] <font color=red>ошибка выставления таймаутов</font>");
string2log(logstr);
CloseHandle(PortToOpen);
return INVALID_HANDLE_VALUE;
}
else {
logstr = tr("] таймауты выставлены");
string2log(logstr);
}
}
return PortToOpen;
}
示例4: assert
bool
Serial::open(QString &err)
{
#ifndef Q_OS_WIN32
//
// Linux and Mac OSX use stdio / termio / tcsetattr
//
assert(fd < 0);
fd = ::open(path.toLatin1().constData(), O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd < 0) {
err = QString("open: ") + strerror(errno);
return false;
}
struct termios tty;
int flags = fcntl(fd, F_GETFL, 0);
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
perror("fcntl");
assert(0);
}
if (tcgetattr(fd, &tty) == -1) {
perror("tcgetattr");
assert(0);
}
tty.c_cflag &= ~CRTSCTS; /* no hardware flow control */
tty.c_cflag &= ~(PARENB | PARODD); /* no parity */
tty.c_cflag &= ~CSTOPB; /* 1 stop bit */
tty.c_cflag &= ~CSIZE; /* clear size bits */
tty.c_cflag |= CS8; /* 8 bits */
tty.c_cflag |= CLOCAL | CREAD; /* ignore modem control lines */
if (cfsetspeed(&tty, B9600) == -1) {
perror("cfsetspeed");
assert(0);
}
tty.c_iflag = IGNBRK; /* ignore BREAK condition on input */
tty.c_lflag = 0;
tty.c_oflag = 0;
tty.c_cc[VMIN] = 1; /* all reads return at least one character */
if (tcsetattr(fd, TCSANOW, &tty) == -1) {
perror("tcsetattr");
assert(0);
}
tcflush(fd, TCIOFLUSH); // clear out the garbage
return true;
#else
Q_UNUSED(err);
//
// Windows uses CreateFile / DCB / SetCommState
//
DCB deviceSettings; // serial port settings baud rate et al
COMMTIMEOUTS timeouts; // timeout settings on serial ports
// if deviceFilename references a port above COM9
// then we need to open "\\.\COMX" not "COMX"
QString portSpec = "\\\\.\\" + path;
wchar_t deviceFilenameW[32]; // \\.\COM32 needs 9 characters, 32 should be enough?
MultiByteToWideChar(CP_ACP, 0, portSpec.toLatin1(), -1, (LPWSTR)deviceFilenameW,
sizeof(deviceFilenameW));
// win32 commport API
fd = CreateFile (deviceFilenameW, GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (fd == INVALID_HANDLE_VALUE) return _isOpen = false;
if (GetCommState (fd, &deviceSettings) == false) return _isOpen = false;
// so we've opened the comm port lets set it up for
deviceSettings.BaudRate = CBR_9600;
deviceSettings.fParity = NOPARITY;
deviceSettings.ByteSize = 8;
deviceSettings.StopBits = ONESTOPBIT;
deviceSettings.EofChar = 0x0;
deviceSettings.ErrorChar = 0x0;
deviceSettings.EvtChar = 0x0;
deviceSettings.fBinary = TRUE;
deviceSettings.fRtsControl = 0x0;
deviceSettings.fOutxCtsFlow = FALSE;
if (SetCommState(fd, &deviceSettings) == false) {
CloseHandle(fd);
return _isOpen = false;
}
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutConstant = 5000;
timeouts.ReadTotalTimeoutMultiplier = 50;
timeouts.WriteTotalTimeoutConstant = 5000;
timeouts.WriteTotalTimeoutMultiplier = 0;
SetCommTimeouts(fd, &timeouts);
return _isOpen = true;
#endif
}
示例5: Java_com_fazecast_jSerialComm_SerialPort_configTimeouts
JNIEXPORT jboolean JNICALL Java_com_fazecast_jSerialComm_SerialPort_configTimeouts(JNIEnv *env, jobject obj, jlong serialPortFD)
{
// Get port timeouts from Java class
HANDLE serialPortHandle = (HANDLE)serialPortFD;
if (serialPortHandle == INVALID_HANDLE_VALUE)
return JNI_FALSE;
COMMTIMEOUTS timeouts = {0};
int timeoutMode = env->GetIntField(obj, timeoutModeField);
DWORD readTimeout = (DWORD)env->GetIntField(obj, readTimeoutField);
DWORD writeTimeout = (DWORD)env->GetIntField(obj, writeTimeoutField);
// Set updated port timeouts
timeouts.WriteTotalTimeoutMultiplier = 0;
switch (timeoutMode)
{
case com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_SEMI_BLOCKING: // Read Semi-blocking
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
timeouts.ReadTotalTimeoutConstant = readTimeout;
timeouts.WriteTotalTimeoutConstant = writeTimeout;
break;
case (com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_SEMI_BLOCKING | com_fazecast_jSerialComm_SerialPort_TIMEOUT_WRITE_SEMI_BLOCKING): // Read/Write Semi-blocking
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
timeouts.ReadTotalTimeoutConstant = readTimeout;
timeouts.WriteTotalTimeoutConstant = writeTimeout;
break;
case (com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_SEMI_BLOCKING | com_fazecast_jSerialComm_SerialPort_TIMEOUT_WRITE_BLOCKING): // Read Semi-blocking/Write Blocking
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
timeouts.ReadTotalTimeoutConstant = readTimeout;
timeouts.WriteTotalTimeoutConstant = writeTimeout;
break;
case com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_BLOCKING: // Read Blocking
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = readTimeout;
timeouts.WriteTotalTimeoutConstant = writeTimeout;
break;
case (com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_BLOCKING | com_fazecast_jSerialComm_SerialPort_TIMEOUT_WRITE_SEMI_BLOCKING): // Read Blocking/Write Semi-blocking
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = readTimeout;
timeouts.WriteTotalTimeoutConstant = writeTimeout;
break;
case (com_fazecast_jSerialComm_SerialPort_TIMEOUT_READ_BLOCKING | com_fazecast_jSerialComm_SerialPort_TIMEOUT_WRITE_BLOCKING): // Read/Write Blocking
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = readTimeout;
timeouts.WriteTotalTimeoutConstant = writeTimeout;
break;
case com_fazecast_jSerialComm_SerialPort_TIMEOUT_SCANNER: // Scanner Mode
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
timeouts.ReadTotalTimeoutConstant = 0x0FFFFFFF;
timeouts.WriteTotalTimeoutConstant = 0;
break;
case com_fazecast_jSerialComm_SerialPort_TIMEOUT_NONBLOCKING: // Non-blocking
default:
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutConstant = 0;
break;
}
// Apply changes
return SetCommTimeouts(serialPortHandle, &timeouts);
}
示例6: CreateFile
bool WinSerialPort::connect(const char *portName, const int baudRate, const size_t inQueueSize, const size_t outQueueSize)
#endif
{
hComPort_ = CreateFile(
portName,
GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
NULL, // default security attributes
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL
);
if (INVALID_HANDLE_VALUE == hComPort_)
{
// Handle the error.
std::cerr << "CreateFile failed with error, " << GetLastError() << ": Port:" << portName << ", BaudRate:" << baudRate << ", Parity:None, Stop bits:1" << std::endl;
//::CloseHandle(hComPort_);
return false;
}
// Set the event mask.
//if (!SetCommMask(hComPort_, EV_CTS | EV_DSR))
if (!SetCommMask(hComPort_, EV_RXCHAR))
{
// Handle the error.
std::cerr << "SetCommMask failed with error: " << GetLastError() << std::endl;
return false;
}
// set sizes of inqueue & outqueue
SetupComm(hComPort_, (DWORD)inQueueSize, (DWORD)outQueueSize);
// purse port
PurgeComm(hComPort_, PURGE_TXABORT | PURGE_TXCLEAR | PURGE_RXABORT | PURGE_RXCLEAR);
// set timeouts
COMMTIMEOUTS timeouts;
timeouts.ReadIntervalTimeout = 0xFFFFFFFF;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 0;
timeouts.WriteTotalTimeoutMultiplier = 2 * CBR_9600 / baudRate;
timeouts.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComPort_, &timeouts);
// set dcb
DCB dcb;
dcb.DCBlength = sizeof(DCB);
GetCommState(hComPort_, &dcb);
//dcb.fBinary = TRUE; // Windows does not support nonbinary mode transfers, so this member must be TRUE
dcb.BaudRate = baudRate;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY; // no parity
dcb.StopBits = ONESTOPBIT; // 1 stop bit
//dcb.fInX = dcb.fOutX = TRUE; // use Xon & Xoff
//dcb.XonChar = SWL_SERIAL_PROTOCOL__ASCII_XON;
//dcb.XoffChar = SWL_SERIAL_PROTOCOL__ASCII_XOFF;
//dcb.XonLim = 100;
//dcb.XoffLim = 100;
if (!::SetCommState(hComPort_, &dcb))
{
std::cerr << "SetCommState failed with error: " << GetLastError() << std::endl;
return false;
}
return true;
}
示例7: RS485_Configure_Status
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();
}
}
示例8: inicializar
void inicializar(){
// Handle to the Serial port
LPCSTR ComPortName = "COM4"; // Name of the Serial port(May Change) to be opened,
BOOL Status; // Status of the various operations
// Bytes read by ReadFile()
int i = 0;
hComm = CreateFile( ComPortName, // Name of the Port to be Opened
GENERIC_READ | GENERIC_WRITE, // Read/Write Access
0, // No Sharing, ports cant be shared
NULL, // No Security
OPEN_EXISTING, // Open existing port only
FILE_ATTRIBUTE_NORMAL, // Non Overlapped I/O
NULL); // Null for Comm Devices
if (hComm == INVALID_HANDLE_VALUE)
printf("\n Error! - Port %s can't be opened\n", ComPortName);
else
printf("Port opened\n");//std::wcout <<"\n Port " << ComPortName << " Opened\n ";
/*------------------------------- Setting the Parameters for the SerialPort ------------------------------*/
DCB dcbSerialParams = { 0 }; // Initializing DCB structure
dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
Status = GetCommState(hComm, &dcbSerialParams); //retrieves the current settings
if (Status == FALSE)
printf("\n Error! in GetCommState()");
dcbSerialParams.BaudRate = CBR_9600; // Setting BaudRate = 9600
dcbSerialParams.ByteSize = 8; // Setting ByteSize = 8
dcbSerialParams.StopBits = ONESTOPBIT; // Setting StopBits = 1
dcbSerialParams.Parity = NOPARITY; // Setting Parity = None
Status = SetCommState(hComm, &dcbSerialParams); //Configuring the port according to settings in DCB
if (Status == FALSE)
{
printf("\n Error! in Setting DCB Structure");
}
else //If Successfull display the contents of the DCB Structure
{
printf("\n\n Setting DCB Structure Successfull\n");
printf("\n Baudrate = %d", dcbSerialParams.BaudRate);
printf("\n ByteSize = %d", dcbSerialParams.ByteSize);
printf("\n StopBits = %d", dcbSerialParams.StopBits);
printf("\n Parity = %d", dcbSerialParams.Parity);
}
/*------------------------------------ Setting Timeouts --------------------------------------------------*/
COMMTIMEOUTS timeouts = { 0 };
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier = 10;
if (SetCommTimeouts(hComm, &timeouts) == FALSE)
printf("\n\n Error! in Setting Time Outs");
else
printf("\n\n Setting Serial Port Timeouts Successfull");
/*------------------------------------ Setting Receive Mask ----------------------------------------------*/
Status = SetCommMask(hComm, EV_RXCHAR); //Configure Windows to Monitor the serial device for Character Reception
if (Status == FALSE)
printf("\n\n Error! in Setting CommMask");
else
printf("\n\n Setting CommMask successfull");
}
示例9: sizeof
RS232::RS232(char *Port,char *Parite,int Vitesse,int Data,char *StopBit,int TimeOut)
{
mutex.lock();
taille_donnee = 20;
DWORD dwError; // n° de l'erreur
BOOL flag_etat; // tout c'est bien passé
wchar_t *pwc = (wchar_t *)malloc( sizeof( wchar_t ));
/*--------------------------------------------------------*/
/* Ouverture du port de Com */
/*--------------------------------------------------------*/
mbstowcs(pwc, Port, 5 );
port_handle = CreateFile(
pwc, // Choix du port « COM »
GENERIC_READ | GENERIC_WRITE, // accès pour lire et écrire sur le port
0, // accès exclusif au port de COM
NULL, // sécurité par défaut
OPEN_EXISTING, // Doit être à cette valeur car se n'est pas un fichier
0, // mode asynchrone
NULL);
/*-----------------------------------------------------------*/
/* Vérifier si handle ouvert correctement */
/*-----------------------------------------------------------*/
if (port_handle == INVALID_HANDLE_VALUE)
{
dwError = GetLastError();
/* Fichier non créer gérer l'erreur */
}
/*-----------------------------------------------------------*/
/* Lecture Configuration initiale */
/*-----------------------------------------------------------*/
creation_ok = GetCommState(port_handle, &configuration);
/*-------------------------------------------------------------------*/
/* Configuration du port */
/*-------------------------------------------------------------------*/
// Gestion de la vitesse
configuration.BaudRate = Vitesse;
// Gestion du nombre de bits
configuration.ByteSize = Data;
// Gestion de la parité
if (strcmp(Parite,"Aucune")==0)
configuration.Parity = NOPARITY;
if (strcmp(Parite,"Paire")==0)
configuration.Parity = EVENPARITY;
if (strcmp(Parite,"Impaire")==0)
configuration.Parity = ODDPARITY;
// Gestion du Stop Bit
if (strcmp(StopBit,"2")==0)
configuration.StopBits = TWOSTOPBITS;
else if (strcmp(StopBit,"1.5")==0)
configuration.StopBits = ONE5STOPBITS;
else
configuration.StopBits = ONESTOPBIT;
// configuration.configurationlength;
configuration.fBinary = 1;
configuration.fParity = 0;
configuration.fOutxCtsFlow = 0;
configuration.fOutxDsrFlow = 0;
configuration.fDtrControl = 0;
configuration.fDsrSensitivity = 0;
configuration.fTXContinueOnXoff = 0;
configuration.fRtsControl = 0;
/*----------------------------------*/
/* Définition des timeouts */
/*----------------------------------*/
temps_attente.ReadIntervalTimeout = MAXWORD;
temps_attente.ReadTotalTimeoutMultiplier = 0;
temps_attente.ReadTotalTimeoutConstant = TimeOut; // pas de time out = 0
temps_attente.WriteTotalTimeoutMultiplier = 0;
temps_attente.WriteTotalTimeoutConstant = 0;
// configurer le timeout
SetCommTimeouts(port_handle,&temps_attente);
/*-----------------------------------------------*/
/* Configurer le port */
/*-----------------------------------------------*/
flag_etat = SetCommState(port_handle, &configuration);
mutex.unlock();
//.........这里部分代码省略.........
示例10: _T
bool ClsSerial::API_Open(UINT uiComPort, DCB &r_Dcb)
{
DWORD dwError = 0;
CString cstrPort;
if( uiComPort >= 10)
cstrPort.Format( _T("\\\\.\\COM%d"), uiComPort);
else
cstrPort.Format( _T("COM%d"), uiComPort);
m_hdlCom =CreateFile( cstrPort,
GENERIC_READ | GENERIC_WRITE,
//0,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
m_hdlRdEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
m_hdlWtEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
m_OverlapRd.hEvent = m_hdlRdEvent;
m_OverlapWt.hEvent = m_hdlWtEvent;
if ( m_hdlCom == INVALID_HANDLE_VALUE ||
m_hdlRdEvent == INVALID_HANDLE_VALUE ||
m_hdlWtEvent == INVALID_HANDLE_VALUE )
{
return false;
}
if (!ClearCommError(m_hdlCom, &dwError, &m_COMSTAT))
{
return false;
}
if (!PurgeComm(m_hdlCom, PURGE_RXCLEAR | PURGE_TXCLEAR))
{
return false;
}
//Set Configuration
if (!GetCommState(m_hdlCom, &m_DCB))
{
return false;
}
m_DCB.BaudRate = r_Dcb.BaudRate;
m_DCB.ByteSize = r_Dcb.ByteSize;
m_DCB.Parity = r_Dcb.Parity;
m_DCB.StopBits = r_Dcb.StopBits;
if (!SetCommState(m_hdlCom, &m_DCB))
{
return false;
}
//Set Buffer
if (!SetupComm(m_hdlCom, 1024, 1024))
{
return false;
}
//Set Timeout
COMMTIMEOUTS time_out;
time_out.ReadIntervalTimeout = MAXDWORD;
time_out.ReadTotalTimeoutConstant = 500;
time_out.ReadTotalTimeoutMultiplier = 20;
time_out.WriteTotalTimeoutConstant = 500;
time_out.WriteTotalTimeoutMultiplier = 20;
if( !SetCommTimeouts(m_hdlCom,&time_out) )
{
return false;
}
return true;
}
示例11: CreateFile
bool SerialPortBase::OpenPort(UnicodeString strCommName,int baud,int stopBits,int parity)
{
// 打开串口
HANDLE hdl = CreateFile(strCommName.c_str(),
GENERIC_READ|GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | FILE_ATTRIBUTE_NORMAL, //正常模式.非异步.
NULL
);
if (hdl == INVALID_HANDLE_VALUE)
{
//打开异常.
return false;
}
this->m_hSerialPort = hdl;
// 读取串口设置.
if (GetCommState(hdl,&m_stSettings) == false)
{
CloseHandle(hdl);
return false;
}
// 修改设置.
m_stSettings.BaudRate = baud;//this->m_iBardRate;
m_stSettings.fParity = parity;//this->m_iParityMode;
m_stSettings.StopBits = stopBits;//this->m_iStopBits;
m_stSettings.ByteSize = 8;
if (SetCommState(hdl,&m_stSettings) == false)
{
CloseHandle(hdl);
return false;
}
// 超时设置.
if (GetCommTimeouts(hdl,&m_stTimeout) == false)
{
CloseHandle(hdl);
return false;
}
// 事件设置.
if(SetCommMask(hdl,EV_RXCHAR | EV_ERR | EV_CTS | EV_DSR | EV_BREAK | EV_TXEMPTY | EV_RING | EV_RLSD)==false)//监控接收事件.
{
CloseHandle(hdl);
return false;
}
//m_stTimeout.ReadTotalTimeoutConstant = 100;
//m_stTimeout.ReadTotalTimeoutMultiplier = 1;
m_stTimeout.ReadIntervalTimeout = 50; // 字符间超时.设置位100ms,若100ms内无数据则认为无法读取数据.
if (SetCommTimeouts(hdl,&m_stTimeout) == false )
{
CloseHandle(hdl);
return false;
}
// 完成设置.
// 清空缓冲区.
PurgeComm(hdl,PURGE_TXABORT | PURGE_RXABORT |PURGE_TXCLEAR |PURGE_RXCLEAR );
if (ovl.hEvent != NULL)
{
ResetEvent(ovl.hEvent);
}
else
{
ovl.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
}
if (ovr.hEvent != NULL)
{
ResetEvent(ovr.hEvent);
}
else
{
ovr.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
}
if (ovw.hEvent != NULL)
{
ResetEvent(ovw.hEvent);
}
else
{
ovw.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
}
this->m_bPortOpen = true;
//pthread->m_bTerminated = false;
//this->pthread->Started
pthread->ThreadResume();
return true;
//.........这里部分代码省略.........
示例12: serio_open_handle
/*-------------------------------------------------------------------------
Open a comm port and get ready for I/O
Call with a pointer to an uninitizlized serio_t.
If you call this, don't call serio_open_handle().
-------------------------------------------------------------------------*/
serio_res_t serio_open(serio_t *serio, long baud, const char *portname)
{
COMMTIMEOUTS CommTimeOuts ;
DCB dcb ;
SECURITY_ATTRIBUTES SecurityAttributes;
HANDLE h;
/*--- Set up Win32 stuff ---*/
if (baud <= CBR_9600) baud = CBR_9600;
else if (baud <= CBR_19200) baud = CBR_19200;
else if (baud <= CBR_38400) baud = CBR_38400;
else baud = CBR_57600;
/* Let child processes inherit this handle. */
memset(&SecurityAttributes, 0, sizeof(SECURITY_ATTRIBUTES));
SecurityAttributes.nLength = sizeof( SECURITY_ATTRIBUTES );
SecurityAttributes.lpSecurityDescriptor = NULL;
SecurityAttributes.bInheritHandle = TRUE;
h = CreateFile(portname, GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
&SecurityAttributes,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL
#ifdef USE_OVERLAP
| FILE_FLAG_OVERLAPPED // overlapped I/O
#endif
, NULL);
if (INVALID_HANDLE_VALUE == h) {
DPRINT(("serio_open: CreateFile(%s...) failed\n", portname));
return serio_RES_BAD;
}
// Set the size of the input and output buffer.
if (!SetupComm( h, 4096, 0 )) {
DPRINT(("serio_open: SetupComm failed\n"));
return serio_RES_BUG;
}
// purge any information in the buffer
if (!PurgeComm( h, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR)) {
DPRINT(("serio_open: PurgeComm failed\n"));
return serio_RES_BUG;
}
// set the time-out parameters for all read and write operations
#if 1
// Cause ReadFile to never wait.
// Works OK in Win95.
CommTimeOuts.ReadIntervalTimeout = MAXDWORD ;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
CommTimeOuts.ReadTotalTimeoutConstant = 0 ;
#elif 0
// Cause ReadFile to wait 50 milliseconds, then time out unconditionally.
// Fails sometimes in Win95; the overlapped read *never* completes.
CommTimeOuts.ReadIntervalTimeout = 0 ;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
CommTimeOuts.ReadTotalTimeoutConstant = 50 ;
#elif 0
// Cause ReadFile to wait 100 milliseconds for traffic to start, but
// wait only 10 milliseconds for traffic to resume if it goes silent
// after starting.
// Fails sometimes in Win95; the overlapped read *never* completes.
CommTimeOuts.ReadIntervalTimeout = 10 ;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
CommTimeOuts.ReadTotalTimeoutConstant = 100 ;
#endif
CommTimeOuts.WriteTotalTimeoutMultiplier = 0 ;
CommTimeOuts.WriteTotalTimeoutConstant = 1000 ; /* will writes timeout? */
if (!SetCommTimeouts( h, &CommTimeOuts )) {
DPRINT(("serio_open: SetCommTimeouts failed\n"));
return serio_RES_BUG;
}
dcb.DCBlength = sizeof( DCB ) ;
if (!GetCommState( h, &dcb)) {
DPRINT(("serio_open: GetCommState failed\n"));
return serio_RES_BUG;
}
dcb.BaudRate = baud;
dcb.Parity = FALSE ;
dcb.fBinary = TRUE ;
dcb.fOutxCtsFlow = FALSE ;
dcb.fOutxDsrFlow = FALSE ;
dcb.Parity = NOPARITY ;
dcb.ByteSize = 8 ;
dcb.StopBits = ONESTOPBIT ;
if (!SetCommState( h, &dcb)) {
DPRINT(("serio_open: SetCommState failed\n"));
//.........这里部分代码省略.........
示例13: FUNC
JNIEXPORT jlong JNICALL FUNC(open0)(JNIEnv *env, jobject jobj, jstring portName, jint baudRate, jint byteSize, jint parity, jint stopBits)
{
const wchar_t * cportName = (const wchar_t *)env->GetStringChars(portName, NULL);
HANDLE handle = CreateFile(cportName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
if (handle == INVALID_HANDLE_VALUE) {
throwIOException(env, "Error opening serial port");
return -1;
}
DCB dcb = { 0 };
if (!GetCommState(handle, &dcb)) {
throwIOException(env, "Error getting DCB");
return -1;
}
dcb.BaudRate = baudRate;
dcb.ByteSize = (BYTE)byteSize;
switch (parity) {
case 0: // None
dcb.fParity = FALSE;
break;
case 1: // Even
dcb.fParity = TRUE;
dcb.Parity = EVENPARITY;
break;
case 2: // Odd
dcb.fParity = TRUE;
dcb.Parity = ODDPARITY;
break;
}
switch (stopBits) {
case 0:
dcb.StopBits = ONESTOPBIT;
break;
case 1:
dcb.StopBits = TWOSTOPBITS;
break;
}
if (!SetCommState(handle, &dcb)) {
throwIOException(env, "Error setting DCB");
return -1;
}
COMMTIMEOUTS timeouts = { 0 };
timeouts.ReadIntervalTimeout = MAXDWORD;
timeouts.ReadTotalTimeoutMultiplier = MAXDWORD;
timeouts.ReadTotalTimeoutConstant = 200;
if (!SetCommTimeouts(handle, &timeouts)) {
throwIOException(env, "Error setting timeouts");
return -1;
}
return (jlong)handle;
}
示例14: OpenComport
int OpenComport(int comport_number, int baudrate)
{
if((comport_number>15)||(comport_number<0))
{
printf("illegal comport number\n");
return(1);
}
switch(baudrate)
{
case 110 : strcpy(baudr, "baud=110 data=8 parity=N stop=1");
break;
case 300 : strcpy(baudr, "baud=300 data=8 parity=N stop=1");
break;
case 600 : strcpy(baudr, "baud=600 data=8 parity=N stop=1");
break;
case 1200 : strcpy(baudr, "baud=1200 data=8 parity=N stop=1");
break;
case 2400 : strcpy(baudr, "baud=2400 data=8 parity=N stop=1");
break;
case 4800 : strcpy(baudr, "baud=4800 data=8 parity=N stop=1");
break;
case 9600 : strcpy(baudr, "baud=9600 data=8 parity=N stop=1");
break;
case 19200 : strcpy(baudr, "baud=19200 data=8 parity=N stop=1");
break;
case 38400 : strcpy(baudr, "baud=38400 data=8 parity=N stop=1");
break;
case 57600 : strcpy(baudr, "baud=57600 data=8 parity=N stop=1");
break;
case 115200 : strcpy(baudr, "baud=115200 data=8 parity=N stop=1");
break;
case 128000 : strcpy(baudr, "baud=128000 data=8 parity=N stop=1");
break;
case 256000 : strcpy(baudr, "baud=256000 data=8 parity=N stop=1");
break;
default : printf("invalid baudrate\n");
return(1);
break;
}
Cport[comport_number] = CreateFileA(comports[comport_number],
GENERIC_READ|GENERIC_WRITE,
0, /* no share */
NULL, /* no security */
OPEN_EXISTING,
0, /* no threads */
NULL); /* no templates */
if(Cport[comport_number]==INVALID_HANDLE_VALUE)
{
printf("unable to open comport\n");
return(1);
}
DCB port_settings;
memset(&port_settings, 0, sizeof(port_settings)); /* clear the new struct */
port_settings.DCBlength = sizeof(port_settings);
if(!BuildCommDCBA(baudr, &port_settings))
{
printf("unable to set comport dcb settings\n");
CloseHandle(Cport[comport_number]);
return(1);
}
if(!SetCommState(Cport[comport_number], &port_settings))
{
printf("unable to set comport cfg settings\n");
CloseHandle(Cport[comport_number]);
return(1);
}
COMMTIMEOUTS Cptimeouts;
Cptimeouts.ReadIntervalTimeout = MAXDWORD;
Cptimeouts.ReadTotalTimeoutMultiplier = 0;
Cptimeouts.ReadTotalTimeoutConstant = 0;
Cptimeouts.WriteTotalTimeoutMultiplier = 0;
Cptimeouts.WriteTotalTimeoutConstant = 0;
if(!SetCommTimeouts(Cport[comport_number], &Cptimeouts))
{
printf("unable to set comport time-out settings\n");
CloseHandle(Cport[comport_number]);
return(1);
}
return(0);
}
示例15: SerialInit
//.........这里部分代码省略.........
case 2:
StopBit = TWOSTOPBITS;
break;
default:
return NULL; // illegal parameter !
}
hCom = CreateFile( ComPortName,
GENERIC_READ | GENERIC_WRITE,
0, // exclusive access
NULL, // no security
OPEN_EXISTING,
0, // no overlapped I/O
NULL); // null template
if(hCom == INVALID_HANDLE_VALUE) return NULL;
bPortReady = SetupComm(hCom, RxBufSize, TxBufSize); // set Rx and Tx buffer sizes
// Port settings are specified in a Data Communication Block (DCB).
bPortReady = GetCommState(hCom, &dcb);
dcb.BaudRate = BaudRate;
dcb.ByteSize = ByteSize;
dcb.Parity = Parity;
dcb.StopBits = StopBit;
dcb.fAbortOnError = TRUE;
switch(Protocol) {
case 'D': // DTR/DSR
case 'd':
// set XON/XOFF
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
// set RTSCTS
dcb.fOutxCtsFlow = FALSE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
// set DSRDTR
dcb.fOutxDsrFlow = TRUE;
dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
break;
case 'R': // RTS/CTS
case 'r':
// set XON/XOFF
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
// set RTSCTS
dcb.fOutxCtsFlow = TRUE;
dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
// set DSRDTR
dcb.fOutxDsrFlow = FALSE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
break;
case 'X': // XON/XOFF
case 'x':
// set XON/XOFF
dcb.fOutX = TRUE;
dcb.fInX = TRUE;
dcb.fTXContinueOnXoff = TRUE;
dcb.XoffChar = ASCII_XOFF;
dcb.XoffLim = RxBufSize - (RxBufSize / 4);
dcb.XonChar = ASCII_XON;
dcb.XonLim = RxBufSize - (RxBufSize / 2);
// set RTSCTS
dcb.fOutxCtsFlow = FALSE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
// set DSRDTR
dcb.fOutxDsrFlow = FALSE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
break;
case 'N': // NOPROTOCOL
case 'n':
default:
// set XON/XOFF
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
// set RTSCTS
dcb.fOutxCtsFlow = FALSE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
// set DSRDTR
dcb.fOutxDsrFlow = FALSE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
break;
}
bPortReady = SetCommState(hCom, &dcb);
// Set timeouts
CommTimeouts.ReadIntervalTimeout = RxTimeOut;
CommTimeouts.ReadTotalTimeoutMultiplier = 0;
CommTimeouts.ReadTotalTimeoutConstant = RxTimeOut;
CommTimeouts.WriteTotalTimeoutMultiplier = 0;
CommTimeouts.WriteTotalTimeoutConstant = TxTimeOut;
bPortReady = SetCommTimeouts(hCom, &CommTimeouts);
return hCom;
}