// Event2Dlg.cpp : implementation file
//

#include "stdafx.h"
#include "Event2.h"
#include "Event2Dlg.h"

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

UINT ThreadProc( LPVOID lpParam );

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

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

wchar_t	  	  szwIPAddress[20];   // store the IP address of 1st 5000/TCP
wchar_t		  szwIPAddress2[20];  // store the IP address of 2nd 5000/TCP
static int    iTotalReceive;
static int    iTotalTimeout;
static int    iThreadIndex;

int      iMatchIndex,iReceiveCount,iThreadRun,iTotalStream=99;
wchar_t  szwFromIP[20];

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

//----------------------------------------------
struct _StreamData   *pStreamData,StreamData;
static BYTE byLoopFlag=1;
HANDLE    hEvent;

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;
}

/////////////////////////////////////////////////////////////////////////////
// CEvent2Dlg dialog

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

void CEvent2Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CEvent2Dlg)
	DDX_Text(pDX, IDC_EDIT_IPADDRESS, m_strIPAddress);
	DDX_Text(pDX, IDC_EDIT_IPADDRESS2, m_strIPAddress2);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CEvent2Dlg, CDialog)
	//{{AFX_MSG_MAP(CEvent2Dlg)
	ON_BN_CLICKED(IDC_START, OnStart)
	ON_BN_CLICKED(IDC_STOP, OnStop)
	ON_BN_CLICKED(IDC_EXIT, OnExit)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CEvent2Dlg message handlers

BOOL CEvent2Dlg::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.1.144";
	SetDlgItemText(IDC_EDIT_IPADDRESS,m_strIPAddress);
	m_strIPAddress2="172.18.1.200";
	SetDlgItemText(IDC_EDIT_IPADDRESS2,m_strIPAddress2);

	// get the DLL version 
	char     szCh[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 !!!") );
    }

    (CButton *)GetDlgItem(IDC_STOP)->EnableWindow( FALSE );
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}



void CEvent2Dlg::OnStart() 
{
	// TODO: Add your control notification handler code here
	int       iRetVal; 
    CString   strText,strTemp;

   (CButton *)GetDlgItem(IDC_START)->EnableWindow( FALSE );
   (CButton *)GetDlgItem(IDC_STOP)->EnableWindow( TRUE );
   (CButton *)GetDlgItem(IDC_EXIT)->EnableWindow( FALSE );

	m_bStopThread = FALSE;
	m_pThread = NULL;

    m_iTotalReceive=0;
    m_iTotalTimeout=0;
    m_iThreadIndex=0;

    // get the 1st 5000/TCP's IP Address
	GetDlgItemText(IDC_EDIT_IPADDRESS,szwIPAddress,20);
    // get the 2nd 5000/TCP's IP Address
	GetDlgItemText(IDC_EDIT_IPADDRESS2,szwIPAddress2,20);

    //-----  create a event for synchronization ---------------
    hEvent = CreateEvent(NULL,
			     FALSE,   // auto reset
			     FALSE,  // init state as Non-Signal
			     NULL);

    //--- adding the first 5000/TCP for streaming ----
    iRetVal=ADAMTCP_Add5KTCPForStream(szwIPAddress);
    if( iRetVal<0 )
    {
		MessageBox(_T("ADAMTCP_Add5KTCPForStream() Failure !!!"));
    }

    //--- adding the second 5000/TCP for streaming ----
    iRetVal=ADAMTCP_Add5KTCPForStream(szwIPAddress2);
    if( iRetVal<0 )
    {
		MessageBox(_T("ADAMTCP_Add5KTCPForStream() Failure !!!"));
    }

	//sprintf(szDump,"Total Receive:%d   Timeout=%d  index=%d",
	//				m_iTotalReceive,m_iTotalTimeout,m_iThreadIndex);
	//MessageBox( TEXT(szDump) );

	((CListBox*)GetDlgItem(IDC_LIST_STREAM))->ResetContent();
    m_pListBox=(CListBox*)GetDlgItem(IDC_LIST_STREAM);
	((CListBox*)GetDlgItem(IDC_LIST_STREAM2))->ResetContent();
    m_pListBox2=(CListBox*)GetDlgItem(IDC_LIST_STREAM2);

	if( m_pThread == NULL )
	{
		m_ThreadData.hEvent = &hEvent;
		m_ThreadData.lpStopThread = &m_bStopThread;
		m_ThreadData.TotalReceive=&m_iTotalReceive;
        m_ThreadData.TotalTimeout=&m_iTotalTimeout;
        m_ThreadData.ThreadIndex=&m_iThreadIndex;
		m_ThreadData.pListBox=m_pListBox;
		m_ThreadData.pListBox2=m_pListBox2;
  	    // Start the thread.
		m_pThread =
			AfxBeginThread(ThreadProc, (LPVOID) &m_ThreadData);
	}

    //--- Starting to receive the streaming data come from 5000/TCP ---
    ADAMTCP_StartStream( &hEvent);	
}

void CEvent2Dlg::OnStop() 
{
	// TODO: Add your control notification handler code here
	HANDLE hThread = m_pThread->m_hThread;

	(CButton *)GetDlgItem(IDC_START)->EnableWindow( TRUE );
    (CButton *)GetDlgItem(IDC_STOP)->EnableWindow( FALSE );
	(CButton *)GetDlgItem(IDC_EXIT)->EnableWindow( TRUE );

	// Set the flag to kill the thread to TRUE;
    m_bStopThread = TRUE;

	// Wait for the thread to end.
	::WaitForSingleObject( hThread, 1000 );

    //--- Stop receiving the streaming data come from 5000/TCP ---	
	ADAMTCP_StopStream( );
    //--- Close the event handle ---
    CloseHandle(hEvent);

    m_iTotalReceive=0;
    m_iTotalTimeout=0;
    m_iThreadIndex=0;	
}

void CEvent2Dlg::OnExit() 
{
	// TODO: Add your control notification handler code here
    //--- calling ADAMTCP_Close() to release all allocated resource  ---
    ADAMTCP_Close();

	CDialog::OnOK();	
}

UINT ThreadProc( LPVOID lpParam )
{
	THREAD_DATA *lpThreadData =
		(THREAD_DATA *) lpParam;
    BOOL   *bStopThread=(BOOL*)lpParam ; 
	int    iRetVal;
    CString   strText; 
	int    iReceive=0,iReceive2=0;

	while( !(*lpThreadData->lpStopThread) )
	{
		*lpThreadData->ThreadIndex=101;
	    if(WaitForSingleObject(*lpThreadData->hEvent,2000)==WAIT_OBJECT_0)  // waiting for 5 seconds
	    { 
              ADAMTCP_Debug(&iMatchIndex, &iReceiveCount, &iThreadRun, &iTotalStream, szwFromIP);
              switch( iMatchIndex )
			  {
			    case 0: 
			     if( iReceive%3==2 )
				 {
				   (lpThreadData->pListBox)->ResetContent();
				 }
			     iReceive++;
	 		     // reading stream data from 1st 5000/TCP
                 iRetVal=ADAMTCP_ReadStreamData(szwIPAddress,&StreamData);
                 pStreamData=(struct _StreamData *)&StreamData;

		         strText.Format( _T("Receive:%d"), iReceive);
		         (lpThreadData->pListBox)->InsertString( -1, strText );
			  
	             strText.Format (_T("DI/DO data of Slot0 to Slot 7:"));
			     (lpThreadData->pListBox)->InsertString( -1, strText );
			     strText.Format(_T("%04x:%04x:%04x:%04x-%04x:%04x:%04x:%04x"),StreamData.DIO[0],StreamData.DIO[1],
							       StreamData.DIO[2],StreamData.DIO[3],
							       StreamData.DIO[4],StreamData.DIO[5],	
							       StreamData.DIO[6],StreamData.DIO[7]);
			     (lpThreadData->pListBox)->InsertString( -1, strText );
			     strText.Format(_T("AI/Ao data of Slot0:"));
			     (lpThreadData->pListBox)->InsertString( -1, strText );
                 strText.Format(_T("%04x:%04x:%04x:%04x-%04x:%04x:%04x:%04x"),StreamData.Slot0[0],StreamData.Slot0[1],
							       StreamData.Slot0[2],StreamData.Slot0[3],
							       StreamData.Slot0[4],StreamData.Slot0[5],
							       StreamData.Slot0[6],StreamData.Slot0[7]);	
			     (lpThreadData->pListBox)->InsertString( -1, strText );
			     strText.Format(_T("AI/AO data of Slot1:"));
			     (lpThreadData->pListBox)->InsertString( -1, strText );
                 strText.Format(_T("%04x:%04x:%04x:%04x-%04x:%04x:%04x:%04x"),StreamData.Slot1[0],StreamData.Slot1[1],
							       StreamData.Slot1[2],StreamData.Slot1[3],
							       StreamData.Slot1[4],StreamData.Slot1[5],
							       StreamData.Slot1[6],StreamData.Slot1[7]);			
			     (lpThreadData->pListBox)->InsertString( -1, strText );

                 break;
				case 1:  
			     if( iReceive2%3==2 )
				 {
				   (lpThreadData->pListBox2)->ResetContent();
				 }
			     iReceive2++;
			     // reading stream data from 2nd 5000/TCP
                 iRetVal=ADAMTCP_ReadStreamData(szwIPAddress2,&StreamData);
		         strText.Format( _T("Receive:%d"),iReceive2);
		         (lpThreadData->pListBox2)->InsertString( -1, strText );
			  
	             strText.Format (_T("DI/DO data of Slot0 to Slot 7:"));
			     (lpThreadData->pListBox2)->InsertString( -1, strText );
			     strText.Format(_T("%04x:%04x:%04x:%04x-%04x:%04x:%04x:%04x"),StreamData.DIO[0],StreamData.DIO[1],
							       StreamData.DIO[2],StreamData.DIO[3],
							       StreamData.DIO[4],StreamData.DIO[5],	
							       StreamData.DIO[6],StreamData.DIO[7]);
			     (lpThreadData->pListBox2)->InsertString( -1, strText );
			     strText.Format(_T("AI/Ao data of Slot0:"));
			     (lpThreadData->pListBox2)->InsertString( -1, strText );
                 strText.Format(_T("%04x:%04x:%04x:%04x-%04x:%04x:%04x:%04x"),StreamData.Slot0[0],StreamData.Slot0[1],
							       StreamData.Slot0[2],StreamData.Slot0[3],
							       StreamData.Slot0[4],StreamData.Slot0[5],
							       StreamData.Slot0[6],StreamData.Slot0[7]);	
			     (lpThreadData->pListBox2)->InsertString( -1, strText );
			     strText.Format(_T("AI/AO data of Slot1:"));
			     (lpThreadData->pListBox2)->InsertString( -1, strText );
                 strText.Format(_T("%04x:%04x:%04x:%04x-%04x:%04x:%04x:%04x"),StreamData.Slot1[0],StreamData.Slot1[1],
							       StreamData.Slot1[2],StreamData.Slot1[3],
							       StreamData.Slot1[4],StreamData.Slot1[5],
							       StreamData.Slot1[6],StreamData.Slot1[7]);			
			     (lpThreadData->pListBox2)->InsertString( -1, strText );
				 break;
			  }

		}
		else
		{
			(*lpThreadData->TotalTimeout)++;
		}

	}
	(*lpThreadData->ThreadIndex)=102;
	return 0;
}
