// Serial.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"



/* A sample program to illustrate setting up a serial port. */

int _tmain(int argc, _TCHAR* argv[])
{
	printf("\nProgram start");

	DCB dcb;
	HANDLE hCom;
	BOOL fSuccess;
	char *pcCommPort = "COM1";
	
	COMMTIMEOUTS timeouts;
	timeouts.ReadIntervalTimeout = 2; 
	timeouts.ReadTotalTimeoutMultiplier = 1;
	timeouts.ReadTotalTimeoutConstant = 1;
	timeouts.WriteTotalTimeoutMultiplier = 0;
	timeouts.WriteTotalTimeoutConstant = 0;


	hCom = CreateFile( pcCommPort,
					GENERIC_READ | GENERIC_WRITE,
					0,    // must be opened with exclusive-access
					NULL, // no security attributes
					OPEN_EXISTING, // must use OPEN_EXISTING
					0,    // not overlapped I/O
					NULL  // hTemplate must be NULL for comm devices
					);

	if (hCom == INVALID_HANDLE_VALUE) 
	{
		// Handle the error.
		printf ("CreateFile failed with error %d.\n", GetLastError());
		return (1);
	}

	// Build on the current configuration, and skip setting the size
	// of the input and output buffers with SetupComm.

	fSuccess = GetCommState(hCom, &dcb);

	if (!fSuccess) 
	{
		// Handle the error.
		printf ("GetCommState failed with error %d.\n", GetLastError());
		return (2);
	}

	// Fill in DCB: 115,200 bps, 8 data bits, no parity, and 1 stop bit.

	dcb.BaudRate = CBR_115200;     // set the baud rate
	dcb.ByteSize = 8;             // data size, xmit, and rcv
	dcb.Parity = NOPARITY;        // no parity bit
	dcb.StopBits = ONESTOPBIT;    // one stop bit

	fSuccess = SetCommState(hCom, &dcb);

	if (!fSuccess) 
	{
		// Handle the error.
		printf ("SetCommState failed with error %d.\n", GetLastError());
		return (3);
	}

	if (!SetCommTimeouts(hCom, &timeouts))
	// Error setting time-outs.


	printf ("Serial port %s successfully reconfigured.\n", pcCommPort);

	
	DWORD dwCommEvent;
	DWORD dwRead;
	char  chRead;
	DWORD lpNumberOfBytesWritten = NULL;

	SetCommMask(hCom, EV_RXCHAR);

	while(1) {
	if (WaitCommEvent(hCom, &dwCommEvent, NULL)) {
		do {
			ReadFile(hCom, &chRead, 1, &dwRead, NULL);

		} while (dwRead);

		WriteFile(hCom, &chRead, 1, &lpNumberOfBytesWritten, NULL);
	}
	else
		// Error in WaitCommEvent
		break;
	}

	while(1)
	{
		if(kbhit()) break;
	}

	return (0);
}
