#include "pch.h"
#include "Rs232cUsb.h"
#include <locale.h>
#include <mmsystem.h>

// Constructor
CRs232cUsb::CRs232cUsb()
	: m_SerialPort(NULL)
	, m_TransferBuffer()
	, m_ReceiveBuffer()
	, m_ReceiveData(_T(""))
{
}

// Destructor
CRs232cUsb::~CRs232cUsb()
{
}

// (1)Connect
BOOL CRs232cUsb::OpenInterface(CString PortName, DWORD BaudRate)
{
	CString ErrorMessage;
	int ErrorCode;

	// Get COM port handle
	PortName = _T("\\\\.\\") + PortName;
	m_SerialPort = CreateFile(PortName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (m_SerialPort == INVALID_HANDLE_VALUE) {
		ErrorCode = GetLastError();
		ErrorMessage = GetLastErrorMessage(ErrorCode);
		MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
		return FALSE;
	}
	// Set communication conditions
	DCB Dcb;
	memset(&Dcb, 0, sizeof(DCB));
	Dcb.DCBlength = sizeof(DCB);
	Dcb.BaudRate = BaudRate;
	Dcb.fBinary = 1;
	Dcb.fParity = 1;
	Dcb.ByteSize = 8;
	Dcb.Parity = NOPARITY;
	Dcb.StopBits = ONESTOPBIT;
	SetCommState(m_SerialPort, &Dcb);
	// Set buffer
	if (SetupComm(m_SerialPort, 15536, 15536) == FALSE) {
		ErrorCode = GetLastError();
		ErrorMessage = GetLastErrorMessage(ErrorCode);
		MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
		return FALSE;
	}
	// Clear buffer
	if (PurgeComm(m_SerialPort, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR) == FALSE) {
		ErrorCode = GetLastError();
		ErrorMessage = GetLastErrorMessage(ErrorCode);
		MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
		return FALSE;
	}
	// Set timeout
	COMMTIMEOUTS Commtimeouts;
	Commtimeouts.ReadIntervalTimeout = 50;
	Commtimeouts.ReadTotalTimeoutConstant = 1000;
	Commtimeouts.ReadTotalTimeoutMultiplier = 0;
	Commtimeouts.WriteTotalTimeoutConstant = 50;
	Commtimeouts.WriteTotalTimeoutMultiplier = 0;
	SetCommTimeouts(m_SerialPort, &Commtimeouts);

	return TRUE;
}

// (2)Disconnect
BOOL CRs232cUsb::CloseInterface()
{
	CString ErrorMessage;
	int ErrorCode;
	BOOL Result;

	Result = CloseHandle(m_SerialPort);													// Close the serial port
	if (Result == FALSE) {
		ErrorCode = GetLastError();
		ErrorMessage = GetLastErrorMessage(ErrorCode);
		MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
	}

	return Result;
}

// (3)Send commands
BOOL CRs232cUsb::SendMsg(CString SendData)
{
	size_t Length;
	DWORD Bytes;
	BOOL Result = FALSE;

	SendData = SendData + _T("\r\n");													// Add a terminator, CR+LR, to transmitted command
#ifdef _UNICODE
	wcstombs_s(&Length, m_TransferBuffer, sizeof(m_TransferBuffer), SendData, _TRUNCATE);	// Converts a wide characters to multibyte characters
	Length = strlen(m_TransferBuffer);
#else
	_tcscpy_s(m_TransferBuffer, sizeof(m_TransferBuffer), SendData);
	Length = _tcslen(m_TransferBuffer);
#endif
	Bytes = 0;
	Result = WriteFile(m_SerialPort, m_TransferBuffer, static_cast<DWORD>(Length), &Bytes, NULL);	// Write data in the transmit buffer

	return Result;
}

// (4)Receive
BOOL CRs232cUsb::ReceiveMsg(DWORD Timeout)
{
	DWORD StartTime;
	CString ErrorMessage;
	int ErrorCode;
	BOOL Result = FALSE;

	m_ReceiveData = _T("");																// Clear received data
	StartTime = timeGetTime();
	// Continue the loop until LF is received
	for (;;) {
		DWORD NumberOfBytesRead = 0;
		if (ReadFile(m_SerialPort, m_ReceiveBuffer, sizeof(m_ReceiveBuffer), &NumberOfBytesRead, NULL) != FALSE) {	// Read data from the receive buffer
			CString strText(m_ReceiveBuffer, NumberOfBytesRead);
			strText.Replace(_T("\r"), _T(""));											// Delete CR in received data
			int Index = strText.Find(_T("\n"));
			if (Index >= 0) {															// End the loop when LF is received
				m_ReceiveData = m_ReceiveData + strText.Mid(0, Index);					// Extract data without LF and the following from the original received data
				Result = TRUE;
				break;
			}
			else {
				m_ReceiveData = m_ReceiveData + strText;								// Save the data
			}
		}
		else {
			m_ReceiveData = _T("Error");
			ErrorCode = GetLastError();
			ErrorMessage = GetLastErrorMessage(ErrorCode);
			MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
			Result = FALSE;
			break;
		}
		// Timeout processing
		if (timeGetTime() > StartTime + Timeout) {
			m_ReceiveData = _T("Timeout");
			ErrorMessage = GetLastErrorMessage(ERROR_TIMEOUT);
			MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
			Result = FALSE;
			break;
		}
	}

	return Result;
}

// (5)Transmit and receive commands
BOOL CRs232cUsb::SendQueryMsg(CString SendData, DWORD Timeout)
{
	BOOL Result;

	Result = SendMsg(SendData);															// Transmit commands
	if (Result == TRUE) {
		if (SendData.Find(_T("?")) != -1) {
			Result = ReceiveMsg(Timeout);												// Receive response when command transmission is succeeded
		}
	}

	return Result;
}

// Get error message
CString CRs232cUsb::GetLastErrorMessage(DWORD MessageId)
{
	PVOID pBuffer = NULL;
	CString ErrorMessage;

	if (FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
		NULL, MessageId, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<PTSTR>(&pBuffer), 0, NULL) == 0 || pBuffer == NULL) {
		return ErrorMessage;
	}
	ErrorMessage = static_cast<PTSTR>(pBuffer);
	LocalFree(pBuffer);

	return ErrorMessage;
}
