/* ** Command & Conquer Red Alert(tm) ** Copyright 2025 Electronic Arts Inc. ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program. If not, see . */ /*********************************************************************************************** *** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S *** *********************************************************************************************** * * * Project Name : Command & Conquer/ WW Library * * * * File Name : WINCOMM.H * * * * Programmer : Steve Tall * * * * Start Date : 1/10/96 * * * * Last Update : January 10th 1996 [ST] * * * *---------------------------------------------------------------------------------------------* * Overview: * * * * Functions for WinModemClass & WinNullModemClass * * * * These classes was created to replace the greenleaf comms functions used in C&C DOS with * * WIN32 API calls. * * * *---------------------------------------------------------------------------------------------* * * * Functions: * * * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ //#include "function.h" #include "wincomm.h" #include "timer.h" #include "keyboard.h" #include "misc.h" #include #include #include #include /* ** Define this to log modem activity to disk. */ //#define LOG_MODEM /* ** Object represents a serial port */ WinModemClass *SerialPort = NULL; /*********************************************************************************************** * WMC::WinModemClass -- WinModemClass constructor * * * * * * * * INPUT: Nothing * * * * OUTPUT: Nothing * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:14PM ST : Created * *=============================================================================================*/ WinModemClass::WinModemClass(void) { /* ** Allocate memory for our internal circular serial input buffer */ SerialBuffer = new unsigned char [SIZE_OF_WINDOWS_SERIAL_BUFFER]; /* ** Initialise the serial buffer pointers */ SerialBufferReadPtr = 0; SerialBufferWritePtr = 0; /* ** Clear the waiting flags */ WaitingForSerialCharRead = FALSE; WaitingForSerialCharWrite = FALSE; /* ** No default abort or echo function */ AbortFunction = NULL; EchoFunction = NULL; /* ** Clear the running error count */ FramingErrors=0; IOErrors=0; BufferOverruns=0; InBufferOverflows=0; ParityErrors=0; OutBufferOverflows=0; /* ** We havnt opened a port yet so... */ PortHandle = 0; } /*********************************************************************************************** * WMC::~WinModemClass -- destructor for WinModemClass * * * * * * * * INPUT: Nothing * * * * OUTPUT: Nothing * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:15PM ST : Created * *=============================================================================================*/ WinModemClass::~WinModemClass(void) { /* ** Close the port */ if (PortHandle){ Serial_Port_Close(); } /* ** Free the serial buffer */ if (SerialBuffer){ delete [] SerialBuffer; } } /*********************************************************************************************** * Get_Registry_Sub_Key -- search a registry key for a sub-key * * * * * * * * INPUT: handle of key to search * * text to search for * * true if old key should be closed when new key opened * * * * OUTPUT: handle to the key we found or 0 * * * * WARNINGS: None * * * * HISTORY: * * 1/12/96 2:11PM ST : Created * *=============================================================================================*/ HKEY Get_Registry_Sub_Key (HKEY base_key, char *search_key, BOOL close) { char class_string[1024]; DWORD string_size = 1024; DWORD num_sub_keys; DWORD longest_sub_key_name; DWORD longest_class_string; DWORD num_value_entries; DWORD longest_value_name_length; DWORD longest_value_data_length; DWORD security_descriptor_length; FILETIME last_write_time; HKEY result_key; DWORD sub_key_buffer_size; char *sub_key_buffer; char *sub_key_class; if (RegQueryInfoKey (base_key, &class_string[0], &string_size, NULL, &num_sub_keys, &longest_sub_key_name, &longest_class_string, &num_value_entries, &longest_value_name_length, &longest_value_data_length, &security_descriptor_length, &last_write_time) != ERROR_SUCCESS) return (0); sub_key_buffer_size = longest_sub_key_name+16; sub_key_buffer = new char [sub_key_buffer_size]; sub_key_class = new char [longest_class_string+1]; for (int key_num=0 ; key_numdwProviderSubType == PST_MODEM){ temp = modem_config->dwProviderOffset; temp += (int)modem_config; modem_caps = (MODEMDEVCAPS*)temp; modem_caps->dwModemOptions &= ~( MDM_COMPRESSION | MDM_ERROR_CONTROL | MDM_FLOWCONTROL_HARD); SetCommConfig(PortHandle, modem_config ,(unsigned)config_size); } } /* ** Set the device timeouts */ timeouts.ReadIntervalTimeout = 10000; //10 seconds between incoming packets timeouts.ReadTotalTimeoutMultiplier = 0; //disable total timeouts timeouts.ReadTotalTimeoutConstant = 0; //disable total timeouts timeouts.WriteTotalTimeoutMultiplier= 0; //disable total timeouts timeouts.WriteTotalTimeoutConstant = 0; //disable total timeouts if (SetCommTimeouts(com_handle, &timeouts) !=TRUE){ Serial_Port_Close(); return (INVALID_HANDLE_VALUE); } return (com_handle); } #endif /*********************************************************************************************** * WMC::Serial_Port_Open -- opens a com port for asyncronous read/write and gets a handle to it* * * * * * * * INPUT: Com port - 0=com1, 1=com2 etc. * * baud rate - bits per second * * parity - true or false * * word length - 5 to 8 bits * * stop bits - 0=1 stop bit, 1=1.5 & 2=2 * * flow control- 0 = none, 1 = hardware * * * * OUTPUT: Handle to port * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:17PM ST : Created * *=============================================================================================*/ HANDLE WinModemClass::Serial_Port_Open (char *device_name, int baud, int parity, int wordlen, int stopbits, int flowcontrol) { HANDLE com_handle; //temporary storage for the port handle DCB device_control; //device control block COMMTIMEOUTS timeouts; //timeout values #if (0) /* ** Map for com port values to device names */ static char com_ids[8][5]={ "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8" }; #endif //(0) int errorval; char errortxt[128]; char devname[266]={"\\\\.\\"}; //device name to open strcat (devname, device_name); PortHandle = 0; /* ** Open the com port for asyncronous reads/writes */ //com_handle = CreateFile (&com_ids[com][0], GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); com_handle = CreateFile (devname, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); if (com_handle == INVALID_HANDLE_VALUE) return (com_handle); PortHandle = com_handle; /* ** Set the size of the windows communication buffers */ SetupComm(com_handle, SIZE_OF_WINDOWS_SERIAL_BUFFER, SIZE_OF_WINDOWS_SERIAL_BUFFER); /* ** Reset any read or write operation and purge the buffers */ PurgeComm (PortHandle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR); /* ** Create an event object for asyncronous reads */ ReadOverlap.Internal = 0; ReadOverlap.InternalHigh = 0; ReadOverlap.Offset = 0; ReadOverlap.OffsetHigh = 0; ReadOverlap.hEvent = CreateEvent (NULL, TRUE, TRUE, NULL); /* ** Create an event object for asyncronous writes */ WriteOverlap.Internal = 0; WriteOverlap.InternalHigh = 0; WriteOverlap.Offset = 0; WriteOverlap.OffsetHigh = 0; WriteOverlap.hEvent = CreateEvent (NULL, TRUE, TRUE, NULL); /* ** Get the current state of the com port as a basis for our device control block */ if (GetCommState (com_handle , &device_control)){ /* ** Communications settings */ device_control.BaudRate = baud; device_control.fParity = parity; device_control.ByteSize = (char)wordlen; device_control.StopBits = (char)(stopbits-1); /* ** Misc settings for flow control etc. */ device_control.fBinary = TRUE; // Binary mode data transfer device_control.fOutxCtsFlow = TRUE; // CTS flow control device_control.fRtsControl = RTS_CONTROL_HANDSHAKE; // RTS flow control device_control.fErrorChar = FALSE; // Dont put an error char into our input stream device_control.fOutxDsrFlow = FALSE; // No DSR flow control device_control.fDtrControl = DTR_CONTROL_ENABLE; // Enable control of DTR line device_control.fOutX = FALSE; // No XON/XOF flow control device_control.fInX = FALSE; // No XON/XOF flow control device_control.fAbortOnError = FALSE; // Device continues to send after an error /* ** Disable hardware flow control if required */ if (!flowcontrol){ device_control.fOutxCtsFlow = FALSE; // CTS flow control device_control.fRtsControl = RTS_CONTROL_DISABLE; // RTS flow control } /* ** Pass the device settings to windows */ if ( !SetCommState (com_handle , &device_control)){ errorval = GetLastError(); sprintf (errortxt, "RA95 -- SetCommState returned error code %d.\n", errorval); OutputDebugString (errortxt); //Serial_Port_Close(); //return (INVALID_HANDLE_VALUE); } }else{ errorval = GetLastError(); sprintf (errortxt, "RA95 -- GetCommState returned error code %d.\n", errorval); OutputDebugString (errortxt); } /* ** Set the device timeouts */ timeouts.ReadIntervalTimeout = 1000; //1 second between incoming bytes will time-out the read timeouts.ReadTotalTimeoutMultiplier = 0; //disable per byte timeouts timeouts.ReadTotalTimeoutConstant = 3000; //Read operations time out after 3 secs if no data received timeouts.WriteTotalTimeoutMultiplier= 500; //Allow 1/2 ms between each char write timeouts.WriteTotalTimeoutConstant = 1000; //Write operations time out after 1 sec + 1/2 sec per char if data wasnt sent if ( !SetCommTimeouts(com_handle, &timeouts) ){ errorval = GetLastError(); sprintf (errortxt, "RA95 -- SetCommTimeouts returned error code %d.\n", errorval); OutputDebugString (errortxt); //Serial_Port_Close(); //return (INVALID_HANDLE_VALUE); } return (com_handle); } /*********************************************************************************************** * WMC::Set_Modem_Dial_Type -- sets dial type to WC_TOUCH_TONE or WC_PULSE * * * * * * * * INPUT: WC_TOUCH_TONE or WC_PULSE * * * * OUTPUT: Nothing * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:22PM ST : Created * *=============================================================================================*/ void WinModemClass::Set_Modem_Dial_Type(WinCommDialMethodType method) { DialingMethod = method; } /*********************************************************************************************** * WMC::Get_Modem_Status -- gets the status of the modem control lines * * * * * * * * INPUT: Nothing * * * * OUTPUT: Modem status. Any of the following bits CTS_SET, DSR_SET, RI_SET or CD_SET * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:24PM ST : Created * *=============================================================================================*/ unsigned WinModemClass::Get_Modem_Status(void) { DWORD modem_stat = 0; unsigned long return_stat = 0; /* ** Get the modem status */ GetCommModemStatus(PortHandle, &modem_stat); /* ** Translate the windows status flags to greenleaf flags */ if (MS_CTS_ON & modem_stat) return_stat |= CTS_SET; if (MS_DSR_ON & modem_stat) return_stat |= DSR_SET; if (MS_RING_ON & modem_stat) return_stat |= RI_SET; if (MS_RLSD_ON & modem_stat) return_stat |= CD_SET; return (return_stat); } /*********************************************************************************************** * WMC::Set_Serial_DTR -- set the state of the modems DTR control line * * * * * * * * INPUT: state - true or false * * * * OUTPUT: Nothing * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:25PM ST : Created * *=============================================================================================*/ void WinModemClass::Set_Serial_DTR(BOOL state) { if (state){ EscapeCommFunction(PortHandle, SETDTR); }else{ EscapeCommFunction(PortHandle, CLRDTR); } } /*********************************************************************************************** * WMC::Serial_Port_Close -- close the port and free the port handle * * * * * * * * INPUT: Nothing * * * * OUTPUT: Nothing * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:26PM ST : Created * *=============================================================================================*/ void WinModemClass::Serial_Port_Close (void) { if (PortHandle){ CloseHandle(PortHandle); PortHandle = 0; } } /*********************************************************************************************** * WMC::Read_Serial_Chars -- copys chars from the windows serial buffer to the class buffer * * * * * * * * INPUT: Nothing * * * * OUTPUT: TRUE if any chars read * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:26PM ST : Created * *=============================================================================================*/ void Smart_Printf( char *format, ... ); BOOL WinModemClass::Read_Serial_Chars (void) { DWORD bytes_read; //amount of data read this time BOOL read_result; //result of ReadFile BOOL overlap_result; //result of GetOverlappedResult DWORD total_bytes_read=0; //total amount of data read int bytes_to_read; int i; /* ** Are we were still waiting for the last read operation to finish? */ if (WaitingForSerialCharRead){ /* ** Check the result of the last read operation */ bytes_read = 0; overlap_result = GetOverlappedResult(PortHandle, &ReadOverlap, &bytes_read, FALSE); /* ** If we got a good result from GetOverlappedResult and data was read then move it ** to our circular buffer */ if (overlap_result){ WaitingForSerialCharRead = FALSE; //Flag that we are no longer waiting for a read if (bytes_read){ for (i=0 ; ibuffer_len) bytes_to_copy = buffer_len; /* ** Loop to copy the data from the internal class buffer to the users buffer */ for (int i=0 ; iCheck()) { //OutputDebugString ("Wincomm - About to call abort function.\n"); int abort = AbortFunction(); sprintf (abuffer ,"Wincomm - About function returned %d.\n", abort); //OutputDebugString (abuffer); if (abort != COMMSUCCESS) return (abort); } /* ** If we had lost focus then abort */ if (AllSurfaces.SurfacesRestored){ //OutputDebugString ("Wincomm - Aborting due to loss of focus.\n"); return (0); } //OutputDebugString ("Wincomm - About to call Read_From_Serial_Port.\n"); dest_ptr += Read_From_Serial_Port((unsigned char*)(buffer + dest_ptr), (int)buffer_len-dest_ptr); sprintf (abuffer, "Wincomm - End of inner do loop. Time is %d.\n", timer.Time()); //OutputDebugString (abuffer); } while (timer.Time() && dest_ptr < buffer_len && !strchr (buffer, 13) ); //OutputDebugString ("Wincomm - Exited inner do loop.\n"); /* ** We need to discard this result if it is just an echo of the 'AT' command we sent */ cr_ptr = strstr(buffer,"AT"); if (cr_ptr){ if (*buffer == 'A' && *(buffer+1) == 'T' && strchr(buffer,13)){ //OutputDebugString ("Wincomm - Discarding command echo.\n"); cr_ptr = strchr(buffer,13); } } /* ** If it wasnt an AT echo then strip off any leading CR/LF characters */ if (!cr_ptr && (*buffer==13 || *buffer==10)){ cr_ptr = strchr(buffer,13); lf_ptr = strchr(buffer,10); if (!cr_ptr || (lf_ptr && lf_ptr < cr_ptr)){ //OutputDebugString ("Wincomm - Stripping CR/LF.\n"); cr_ptr = strchr(buffer,10); } } /* ** Copy the good stuff at the end of the buffer over the 'AT' or CR/LF chars */ if (cr_ptr){ //OutputDebugString ("Wincomm - Copying over start of buffer.\n"); while(*cr_ptr == 13 || *cr_ptr == 10){ cr_ptr++; } if (cr_ptr != buffer){ copy_bytes = (int)cr_ptr - (int)buffer; memcpy(buffer, cr_ptr, buffer_len - copy_bytes); dest_ptr -= copy_bytes; } } //OutputDebugString ("Wincomm - End of outer do loop.\n"); }while(cr_ptr); /* ** Terminate the string at the first CR character as this is what Greenleaf does */ if (strchr(buffer, 13)){ //OutputDebugString ("Truncating result string.\n"); *(strchr(buffer, 13)) = 0; } //sprintf (abuffer, "Wincomm - returning remaining delay of %d.\n", timer.Time()); //OutputDebugString (abuffer); return (timer.Time()); } /*********************************************************************************************** * WMC::Dial_Modem -- issue an 'ATD' command to the modem * * * * * * * * INPUT: string - number to dial * * * * OUTPUT: Nothing * * * * WARNINGS: Use Set_Modem_Dial_Type to choose pulse or tone dialling * * * * HISTORY: * * 1/10/96 2:32PM ST : Created * *=============================================================================================*/ void WinModemClass::Dial_Modem(char *dial_number) { char dial_string[80]; /* ** Create the dial command to send to the modem */ strcpy (dial_string, "ATD"); if (DialingMethod == WC_TOUCH_TONE){ strcat(dial_string, "T"); }else{ strcat(dial_string, "P"); } /* ** Stick a carriage return on the end */ strcat (dial_string, dial_number); strcat (dial_string, "\r"); /* ** Write the dial command to the serial port and wait for the write to complete */ Write_To_Serial_Port ((unsigned char*)dial_string, strlen(dial_string)); Wait_For_Serial_Write(); } /*********************************************************************************************** * WMC::Send_Command_To_Modem -- send an 'AT' command to the modem and await a response * * * * * * * * INPUT: command string * * terminator byte (usually "\r") * * ptr to buffer to receive modem result code * * length of buffer * * timeout delay for waiting for result * * number of times to retry the command * * * * OUTPUT: result code * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:33PM ST : Created * *=============================================================================================*/ int WinModemClass::Send_Command_To_Modem(char *command, char terminator, char *buffer, int buflen, int delay, int retries) { int times; unsigned char tmp_string[80]; char tmp_buff[80]; char term_string[2]; int time; /* ** Build the terminator string */ term_string[0] = terminator; term_string[1] = 0; /* ** Create the command from the supplied command and terminator */ strcpy((char*)tmp_string, command); strcat((char*)tmp_string, term_string); /* ** Flush out any pending characters from the port */ unsigned char nothing_buff[80]; Read_From_Serial_Port(nothing_buff,80); Sleep (100); Read_From_Serial_Port(nothing_buff,80); for (times = 0 ; times= '0' && tmp_buff[0] <='9') && (tmp_buff[1] >= '0' && tmp_buff[1] <='9') && (tmp_buff[2] >= '0' && tmp_buff[2] <='9')) { strncpy(buffer, tmp_buff, MIN(buflen, 80)); return (MODEM_CMD_OK); } } /* ** It was a non-standard(ish) result so copy it to the users buffer */ strncpy(buffer, tmp_buff, MIN(buflen, 80)); /* ** Spurious write for no apparent reason. Well it was there in the DOS version so... */ Sleep (100); Write_To_Serial_Port((unsigned char*)"\r",1); Wait_For_Serial_Write(); Sleep (100); } return (ASTIMEOUT); } /*********************************************************************************************** * WMC::Set_Echo_Function -- set up the echo function pointer * * * * * * * * INPUT: ptr to echo function * * * * OUTPUT: Nothing * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:35PM ST : Created * *=============================================================================================*/ void WinModemClass::Set_Echo_Function( void ( *func )( char c) ) { EchoFunction = func; } /*********************************************************************************************** * WMC::Set_Abort_Function -- set up the abort function pointer * * * * * * * * INPUT: ptr to abort function * * * * OUTPUT: Nothing * * * * WARNINGS: None * * * * HISTORY: * * 1/10/96 2:35PM ST : Created * *=============================================================================================*/ void WinModemClass::Set_Abort_Function(int (*func)(void)) { AbortFunction = func; } /*********************************************************************************************** * WMC::Get_Port_Handle -- returns a handle to the communications port * * * * * * * * INPUT: Nothing * * * * OUTPUT: Com port handle * * * * WARNINGS: None * * * * HISTORY: * * 5/23/96 1:25PM ST : Created * *=============================================================================================*/ HANDLE WinModemClass::Get_Port_Handle(void) { return (PortHandle); }