enum SERIAL_RESULT_TYPE {
SERIAL_OK = 0, // Everything's OK.
SERIAL_PORT_NOT_INIT, // Can't do this until the port is initialized
SERIAL_PORT_ALREADY_OPENED, // Can't re-open an already-opened serial port
SERIAL_CANNOT_CREATE_THREAD,// Can't create the secondary thread necessary
SERIAL_CANNOT_CREATE_MUTEX, // Can't create the mutex object for the data
SERIAL_CANNOT_INIT_PORT, // Can't open the serial port (bad settings)
SERIAL_UNABLE_TO_LOCK, // Unable to lock NMEA data
SERIAL_UNABLE_TO_UNLOCK, // Unable to unlock NMEA data
SERIAL_WIN32_ERROR // OS-specific error. (Call GetLastError())
};
{
if (m_isConnected == TRUE) {
return SERIAL_PORT_ALREADY_OPENED;
}
char comString[10]; // Contains enough room for 'ComXxx'.
char settingsString[15]; // Contains enough room for '115200,n,8,1.5'.
char stopBitNum[4]; // Contains enough room for '1', '1.5', or '2'.
char parityChar; // Contains the letter (n)one, (e)ven, or (o)dd.
sprintf (comString, "COM%d", comPort);
m_hPort = CreateFile (
comString,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
0,
NULL
);
if (m_hPort != INVALID_HANDLE_VALUE) {
// Serial port exists. Set the parity and stop bits.
switch (parity) {
case SETPARITY_NONE: parityChar = 'n'; break;
case SETPARITY_EVEN: parityChar = 'e'; break;
case SETPARITY_ODD : parityChar = 'o'; break;
}
switch (stopBits) {
case STOPBITS_ONE : strcpy (stopBitNum, "1" ); break;
case STOPBITS_ONEFIVE: strcpy (stopBitNum, "1.5"); break;
case STOPBITS_TWO : strcpy (stopBitNum, "2" ); break;
}
sprintf (settingsString, "%d,%c,%d,%s", baudRate, parityChar,
dataBits, stopBitNum);
// Attempt to connect to the serial port.
if (!SetupComm (m_hPort, 4096, 4096)) {
CloseHandle (m_hPort);
return SERIAL_CANNOT_INIT_PORT;
}
// Specify the com port read timeouts.
COMMTIMEOUTS commTimeouts;
commTimeouts.ReadIntervalTimeout = 0;
commTimeouts.ReadTotalTimeoutMultiplier = 0;
commTimeouts.ReadTotalTimeoutConstant = m_timeout;
commTimeouts.WriteTotalTimeoutMultiplier = 0;
commTimeouts.WriteTotalTimeoutConstant = 0;
// Create a DCB (device control block) for the serial port. A DCB
// contains com port settings. Clear the initial junk out of it.
DCB dcb;
ZeroMemory (&dcb, sizeof (DCB));
// Initialize the DCB values with the correct values given the baud
// rate, parity, number of stop bits, and number of data bits.
if (!BuildCommDCB (settingsString, &dcb)) {
CloseHandle (m_hPort);
return SERIAL_CANNOT_INIT_PORT;
}
// Set the com port parameters.
if ((!SetCommState (m_hPort, &dcb))
|| (!SetCommTimeouts (m_hPort, &commTimeouts))) {
CloseHandle (m_hPort);
return SERIAL_CANNOT_INIT_PORT;
}
// Create the thread that will constantly read strings given the
// serial port handle.
SERIAL_RESULT_TYPE status = InitThread ();
if (status != SERIAL_OK) {
CloseHandle (m_hPort);
return status;
}