// RegReadDlg.cpp : implementation file
//

#include "stdafx.h"
#include "RegRead.h"
#include "RegReadDlg.h"

#include "..\..\include\AdamTcpCE.h"

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

wchar_t	szwIPAddress[20];

int MbsToWcs (char* mbs, wchar_t* wcs);
int WcsToMbs (wchar_t* wcs, char* mbs);

#define  DeviceID       0x01  // 0x01 indicate the 5000/TCP
#define  DEFAULT_PORT   502  // Port for Modbus/TCP
//-------- default timeout ------
int      iConnectionTimeout=5000;
int      iSendTimeout=5000;
int      iReceiveTimeout=5000;

int MbsToWcs (char* mbs, wchar_t* wcs)
{
	wchar_t g_wcConverter[256];
	size_t len = strlen (mbs);
	memset (g_wcConverter, 0, sizeof(g_wcConverter));
	if (len > 127) return NULL;
	mbstowcs(g_wcConverter, mbs, len);
	wcscpy(wcs, g_wcConverter);
	return len;
}

int WcsToMbs (wchar_t* wcs, char* mbs)
{
	char	g_mbConvert[256];
	size_t len = wcslen (wcs);
	if (len >= sizeof(g_mbConvert)) len = sizeof(g_mbConvert) - 1;
	wcstombs(g_mbConvert, wcs, len);
	strcpy(mbs, g_mbConvert);
	return len;
}

/////////////////////////////////////////////////////////////////////////////
// CRegReadDlg dialog

CRegReadDlg::CRegReadDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CRegReadDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CRegReadDlg)
	m_strDeviceID = _T("");
	m_strDLLVersion = _T("");
	m_strIPAddress = _T("");
	m_strNoOfRead = _T("");
	m_strStartAddress = _T("");
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CRegReadDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CRegReadDlg)
	DDX_Text(pDX, IDC_EDIT_DEVICEID, m_strDeviceID);
	DDX_Text(pDX, IDC_EDIT_DLLVER, m_strDLLVersion);
	DDX_Text(pDX, IDC_EDIT_IPADDRESS, m_strIPAddress);
	DDX_Text(pDX, IDC_EDIT_NOOFREAD, m_strNoOfRead);
	DDX_Text(pDX, IDC_EDIT_STARTADDRESS, m_strStartAddress);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CRegReadDlg, CDialog)
	//{{AFX_MSG_MAP(CRegReadDlg)
	ON_BN_CLICKED(IDC_READREGISTER, OnReadregister)
	ON_BN_CLICKED(IDC_EXIT, OnExit)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRegReadDlg message handlers

BOOL CRegReadDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	CenterWindow(GetDesktopWindow());	// center to the hpc screen

	// TODO: Add extra initialization here
	m_strIPAddress="172.18.3.180";
	m_strDeviceID="1";
	m_strStartAddress="1";
	m_strNoOfRead="8";

	SetDlgItemText(IDC_EDIT_IPADDRESS,m_strIPAddress);
	SetDlgItemText(IDC_EDIT_DEVICEID,m_strDeviceID);
	SetDlgItemText(IDC_EDIT_STARTADDRESS,m_strStartAddress);
	SetDlgItemText(IDC_EDIT_NOOFREAD,m_strNoOfRead);

	// get the DLL version 
	char     szCh[20];
	//wchar_t  szwCh[20];
    int    iVersion;    
 
	iVersion=ADAMTCP_GetDLLVersion();
	_ltoa( iVersion, szCh, 16 );

	size_t len = strlen (szCh);
	wchar_t  wcConverter[20];

	memset (wcConverter, 0, sizeof(wcConverter));

	mbstowcs(wcConverter, szCh, len);
	//wsprintf(szwCh,"%s",szCh);
	SetDlgItemText(IDC_EDIT_DLLVER, wcConverter);

    //--- To initialize DLL to work ---
    int   iRetVal;

    iRetVal=ADAMTCP_Open();
    if( iRetVal!=0 )
    {
        MessageBox(_T("ADAMTCP_Open() Failure !!!"));
    }	
	
	//--- reset the content in CListBox ---
	((CListBox*)GetDlgItem(IDC_LIST_REGISTERVALUE))->ResetContent();

	return TRUE;  // return TRUE  unless you set the focus to a control
}



void CRegReadDlg::OnReadregister() 
{
	// TODO: Add your control notification handler code here
    CString   strText,strTemp;
	int       i,j,iRetVal;
	WORD      wDeviceID;
    WORD      wStartAddress;
    WORD      wCount;
    WORD      wData[64];  
	TCHAR	  szwTemp[80];
	TCHAR     szwDump[80];
	char      szTemp[80];
	float     fData;

	// How many registers to read
	GetDlgItemText(IDC_EDIT_NOOFREAD,szwTemp, 80*sizeof(TCHAR));
	iRetVal = WcsToMbs (szwTemp, szTemp);	szTemp[iRetVal] = 0;
	wCount=atoi(szTemp);
	if( wCount<0 || wCount>64 )
	{
		MessageBox( _T("The # of Coil must between 1 to 64 !") );
		return;
	}

	// the Device ID
	GetDlgItemText(IDC_EDIT_DEVICEID,szwTemp, 80*sizeof(TCHAR));
	iRetVal = WcsToMbs (szwTemp, szTemp);	szTemp[iRetVal] = 0;
	wDeviceID=atoi(szTemp);

	// the start address to read
	//-- Notice: the address start at 1 instead of 40001
	GetDlgItemText(IDC_EDIT_STARTADDRESS,szwTemp, 80*sizeof(TCHAR));
	iRetVal = WcsToMbs (szwTemp, szTemp);	szTemp[iRetVal] = 0;
	wStartAddress=atoi(szTemp);

    // get the 5000/TCP's IP Address
	GetDlgItemText(IDC_EDIT_IPADDRESS,szwIPAddress,20);
    
	//--- try to create a connection to 5000/TCP ---
    iRetVal=ADAMTCP_Connect(szwIPAddress,DEFAULT_PORT,
				  iConnectionTimeout, iSendTimeout, iReceiveTimeout);
    if( iRetVal<0 )
    {
        wsprintf(szwDump,_T("ADAMTCP_Connect() Failure !!!   code=%d"),iRetVal);
        MessageBox(szwDump);
		ADAMTCP_Disconnect();
        return;
    }

    //--- reading the registers ---
    iRetVal=ADAMTCP_ReadReg(szwIPAddress, wDeviceID, wStartAddress, wCount, wData);
    if( iRetVal )
    {
		wsprintf(szwDump,_T("ADAMTCP_ReadReg() Failure !!!   code=%d"),iRetVal);
        MessageBox( szwDump );
        ADAMTCP_Disconnect();
        return;
    }

	((CListBox*)GetDlgItem(IDC_LIST_REGISTERVALUE))->ResetContent();
	for(i=0,j=wStartAddress; i<wCount; i++,j++)
	{
		fData = (float)(wData[i]*20.0f/65536.0f) - 10.0f;
		strText.Format( _T("Addr.:%d  Value(Dec):%5d  Value(Hex):%04x Voltage:%2.3f"), j,wData[i],wData[i], fData);
		((CListBox*)GetDlgItem(IDC_LIST_REGISTERVALUE))->InsertString( -1, strText );
	}

    //--- lastly, disconnt connection to 5000/TCP ---
    ADAMTCP_Disconnect();	
}

void CRegReadDlg::OnExit() 
{
	// TODO: Add your control notification handler code here
    ADAMTCP_Close();	
	
	// TODO: Add your control notification handler code here
	CDialog::OnOK();	
}
