// Serial.cpp: implementation of the CSerial class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Capture.h"
#include "Serial.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CSerial::CSerial()
{

}

CSerial::~CSerial()
{

}

int CSerial::Open()
{
	DCB dcb;
	DWORD dwError;
	BOOL fSuccess;
	COMMTIMEOUTS Timeout;

	hCom = CreateFile("COM1",
		GENERIC_READ | GENERIC_WRITE,
		0, //comm devices must be opened w/exclusive-access
		NULL, //no security attributes
		OPEN_EXISTING, //comm devices must use OPEN_EXISTING
		0, //no overlapped I/O
		NULL //hTemplate must be NULL for comm devices
		);

	if (hCom == INVALID_HANDLE_VALUE)
	{
		dwError = GetLastError();
		return 0; //can't open the port
	}

	//omit the call to SetupComm to use the deafult queue sizes
	//Get the current configuration.

	fSuccess = GetCommState(hCom, &dcb);

	if (!fSuccess)
	{
		CloseHandle(hCom);
		return 0;
	}

	//fill in the DCB: baud = 9600, 8 data bits, no parity, 1 stop bit

	dcb.BaudRate = 9600;
	dcb.ByteSize = 8;
	dcb.Parity = NOPARITY;
	dcb.StopBits = ONESTOPBIT;

	fSuccess = SetCommState(hCom, &dcb);

	if (!fSuccess)
	{
		CloseHandle(hCom);
		return 0;
	}

	fSuccess = GetCommTimeouts(hCom, &Timeout);

	if (!fSuccess)
	{
		CloseHandle(hCom);
		return 0;
	}

	Timeout.ReadIntervalTimeout = 500;
	Timeout.ReadTotalTimeoutConstant = 10;
	Timeout.ReadTotalTimeoutMultiplier = 500;

	fSuccess = SetCommTimeouts(hCom, &Timeout);

	if (!fSuccess)
	{
		CloseHandle(hCom);
		return 0;
	}

	return 1;
}

int CSerial::Close()
{
	return CloseHandle(hCom);
}

int CSerial::SendLine(CString command)
{
	command = command + (char) 13 + (char) 10;
	TRACE(command);
	LPSTR s = command.GetBuffer(0);
	DWORD ComLen = command.GetLength();
	DWORD l;

	WriteFile(hCom, s, ComLen, &l, NULL);
	if (l == ComLen)
		return 1;
	else
		return 0;
}

CString CSerial::ReceiveLine()
{
	char inputch = 'a';
	char *ipch = &inputch;
	CString output = "";
	DWORD ipbyte;

	while (inputch != (char)10)
	{
		ReadFile(hCom, ipch, 1, &ipbyte, NULL);
		if (ipbyte == 1)
			output = output + inputch;
		else
			return "";
	}
	return output;
}

