#include "pch.h"
#include "GpibNi.h"
#include <locale.h>
#include <mmsystem.h>
#include "ni4882.h"

// Constructor
CGpibNi::CGpibNi()
	: m_GpibDevice(0)
	, m_TransferBuffer()
	, m_ReceiveData(_T(""))
{
}

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

// (1)Connect
BOOL CGpibNi::OpenInterface(int BoardID, int DeviceAddress)
{
	CString ErrorMessage;

	m_GpibDevice = ibdev(BoardID, DeviceAddress, 0, T1s, 1, 0);							// Create a GPIB object
	if ((Ibsta() & ERR) != 0) {
		ErrorMessage = GetNIErrorMessage();
		MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
		return FALSE;
	}

	ibclr(m_GpibDevice);																// Initialise GPIB
	if ((Ibsta() & ERR) != 0) {
		ErrorMessage = GetNIErrorMessage();
		MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
		return FALSE;
	}

	return TRUE;
}

// (2)Disconnect
BOOL CGpibNi::CloseInterface()
{
	CString ErrorMessage;

	ibonl(m_GpibDevice, 0);																// Take GPIB device offline
	if ((Ibsta() & ERR) != 0) {
		ErrorMessage = GetNIErrorMessage();
		MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
		return FALSE;
	}

	return TRUE;
}

// (3)Send commands
BOOL CGpibNi::SendMsg(CString SendData)
{
	size_t Length;
	CString ErrorMessage;

#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
	ibwrt(m_GpibDevice, m_TransferBuffer, Length);										// Write data in the transmit buffer
	if ((Ibsta() & ERR) != 0) {
		ErrorMessage = GetNIErrorMessage();
		MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
		return FALSE;
	}

	return TRUE;
}

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

	m_ReceiveData = _T("");																// Clear received data
	StartTime = timeGetTime();
	// Continue the loop until LF is received
	for (;;) {
		ibrd(m_GpibDevice, m_TransferBuffer, sizeof(m_TransferBuffer) - 1);				// Read to receive buffer
		if ((Ibsta() & ERR) != 0) {
			if ((Ibsta() & TIMO) == 0) {
				// Other than timeout.
				m_ReceiveData = _T("Error");
				ErrorMessage = GetNIErrorMessage();
				MessageBox(NULL, ErrorMessage, AfxGetAppName(), MB_ICONERROR | MB_OK);
				Result = FALSE;
				break;
			}
			if (Ibcnt() != 0) {
				m_TransferBuffer[Ibcnt()] = '\0';
				CString strText(m_TransferBuffer, Ibcnt());
				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 {
			if (Ibcnt() != 0) {
				m_TransferBuffer[Ibcnt()] = '\0';
				CString strText(m_TransferBuffer, Ibcnt());
				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
				}
			}
		}
		// 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 TRUE;
}

// (5)Transmit and receive commands
BOOL CGpibNi::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 CGpibNi::GetNIErrorMessage()
{
	CString strMessage;
	const static TCHAR *pErrorMnemonic[] = {
		_T("EDVR"),	_T("ECIC"),	_T("ENOL"),	_T("EADR"),	_T("EARG"),
		_T("ESAC"),	_T("EABO"),	_T("ENEB"),	_T("EDMA"),	_T(""),
		_T("EOIP"),	_T("ECAP"),	_T("EFSO"),	_T(""),		_T("EBUS"),
		_T("ESTB"),	_T("ESRQ"),	_T(""),		_T(""),		_T(""),
		_T("ETAB"),	_T("ELCK"),	_T("EARM"),	_T("EHDL"),	_T(""),
		_T(""),		_T("EWIP"),	_T("ERST"),	_T("EPWR")
	};

	strMessage.Format(_T("ibsta = 0x%04x, iberr = %d, %s"), Ibsta(), Iberr(), pErrorMnemonic[Iberr()]);

	return strMessage;
}

// Get error message
CString CGpibNi::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;
}
