// RFC1006DemoDlg.cpp : implementation file
//

#include "stdafx.h"
#include "RFC1006Demo.h"
#include "RFC1006DemoDlg.h"
#include "Rfc1006lib.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRFC1006DemoDlg dialog

CRFC1006DemoDlg::CRFC1006DemoDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CRFC1006DemoDlg::IDD, pParent)
  , m_KeepAlive(1000)
{
	//{{AFX_DATA_INIT(CRFC1006DemoDlg)
	m_TxTimeout = 5000;
	m_RxTimeout = 1;
	m_ConnectTimeout = 5000;
	m_DstTSAP = _T("TCP_S7");
	m_SrcTSAP = _T("TCP_S7");
	m_IPAdr = _T("127.0.0.1");
	m_strStatus = _T("");
	m_Port = 102;
	m_bServer = FALSE;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
  m_Ref = -1;
  m_bServer = TRUE;
  
}

void CRFC1006DemoDlg::DoDataExchange(CDataExchange* pDX)
{
  CDialog::DoDataExchange(pDX);
  //{{AFX_DATA_MAP(CRFC1006DemoDlg)
  DDX_Control(pDX, IDC_RXDATA_HEX, m_ctrlRxDataHex);
  DDX_Control(pDX, IDC_TXDATA_HEX, m_ctrlTxDataHex);
  DDX_Control(pDX, IDC_SRCTSAP_HEX, m_ctrlSrcTSAPHex);
  DDX_Control(pDX, IDC_DSTSAP_HEX, m_ctrlDstTSAPHex);
  DDX_Control(pDX, IDC_DATATOSEND, m_ctrlTxData);
  DDX_Control(pDX, IDC_DATARECEIVED, m_ctrlRxData);
  DDX_Control(pDX, IDC_SRCTSAP, m_ctrlSrcTSAP);
  DDX_Control(pDX, IDC_DSTTSAP, m_ctrlDstTSAP);
  DDX_Text(pDX, IDC_TXTIMEOUT, m_TxTimeout);
  DDV_MinMaxLong(pDX, m_TxTimeout, -1, 20000);
  DDX_Text(pDX, IDC_RXTIMEOUT, m_RxTimeout);
  DDV_MinMaxLong(pDX, m_RxTimeout, -1, 20000);
  DDX_Text(pDX, IDC_CONNECTTIMEOUT, m_ConnectTimeout);
  DDV_MinMaxLong(pDX, m_ConnectTimeout, -1, 20000);
  DDX_Text(pDX, IDC_IPADR, m_IPAdr);
  DDV_MaxChars(pDX, m_IPAdr, 255);
  DDX_Text(pDX, IDC_STATUS, m_strStatus);
  DDX_Text(pDX, IDC_PORT, m_Port);
  DDV_MinMaxUInt(pDX, m_Port, 0, 65565);
  DDX_Check(pDX, IDC_SERVER, m_bServer);
  //}}AFX_DATA_MAP
  if (!pDX->m_bSaveAndValidate)
  {
    m_ctrlSrcTSAP.SetData (m_SrcTSAP, m_SrcTSAP.GetLength ());
    m_ctrlDstTSAP.SetData (m_DstTSAP, m_DstTSAP.GetLength ());
    m_ctrlTxData.SetData (m_strTxData, m_strTxData.GetLength ());
    m_ctrlRxData.SetData (m_strRxData, m_strRxData.GetLength ());
  }
  else
  {
    long L;
    m_ctrlSrcTSAP.GetData (m_SrcTSAP, 255, L);
    m_ctrlDstTSAP.GetData (m_DstTSAP, 255, L);
    m_ctrlTxData.GetData (m_strTxData, 2048, L);
    m_ctrlRxData.GetData (m_strRxData, 2048, L);
  }
  DDX_Text(pDX, IDC_KEEPALIVE, m_KeepAlive);
	DDV_MinMaxLong(pDX, m_KeepAlive, 500, 60000);
}

BEGIN_MESSAGE_MAP(CRFC1006DemoDlg, CDialog)
	//{{AFX_MSG_MAP(CRFC1006DemoDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_OPEN, OnOpen)
	ON_BN_CLICKED(IDC_CLOSE, OnClose)
	ON_BN_CLICKED(IDC_CONNECT, OnConnect)
	ON_BN_CLICKED(IDC_GET_STATUS, OnGetStatus)
	ON_BN_CLICKED(IDC_TXDATA, OnTxData)
	ON_BN_CLICKED(IDC_RXDATA, OnRxData)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_SRCTSAP_HEX, OnSrcTSAPHex)
	ON_BN_CLICKED(IDC_DSTSAP_HEX, OnDstSAPHex)
	ON_BN_CLICKED(IDC_TXDATA_HEX, OnTxDataHex)
	ON_BN_CLICKED(IDC_RXDATA_HEX, OnRxDataHex)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CRFC1006DemoDlg message handlers

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

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 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
	
	// TODO: Add extra initialization here
	SetTimer (1, 1000, NULL);
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CRFC1006DemoDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CRFC1006DemoDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CRFC1006DemoDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CRFC1006DemoDlg::OnOpen() 
{
  if (UpdateData (TRUE))
  {
    if (m_bServer)
    {
      int Res;
      
      m_Ref = Rfc1006OpenServer (m_IPAdr, (BYTE *) (const char *)m_SrcTSAP, m_SrcTSAP.GetLength (), (BYTE *) (const char *)m_DstTSAP, m_DstTSAP.GetLength ());
      if (m_Ref >= 0 && m_KeepAlive > 0)
        Rfc1006SetKeepAlive( m_Ref, 1000, m_KeepAlive);

      Res = Rfc1006StartServer (m_Port, "", 16);      

      if (Res != 0)
      {
          Rfc1006Close (m_Ref);
          m_Ref = -1;
          ShowStatus(Res);   
          ////CString S;
          ////S.Format ("Res = %d", Res);
          ////AfxMessageBox(S);
      }
    }
    else
    {
       m_Ref = Rfc1006Open (m_IPAdr, (BYTE *) (const char *)m_SrcTSAP, m_SrcTSAP.GetLength (), (BYTE *) (const char *)m_DstTSAP, m_DstTSAP.GetLength (), 
                             m_Port, m_ConnectTimeout);
       if (m_Ref >= 0 && m_KeepAlive > 0)
         Rfc1006SetKeepAlive( m_Ref, 1000, m_KeepAlive);
    }
    if (m_Ref >= 0)
    {

      EnableDlgItem (IDC_OPEN, FALSE);
      EnableDlgItem (IDC_CLOSE);
      EnableDlgItem (IDC_GET_STATUS);
      EnableDlgItem (IDC_RXDATA);
      EnableDlgItem (IDC_TXDATA);
      EnableDlgItem (IDC_CONNECT, !m_bServer);
    }

  }
}

void CRFC1006DemoDlg::OnClose() 
{
  if (m_Ref >= 0)
  {
    Rfc1006Close (m_Ref);
    if (m_bServer)
    {
      Rfc1006StopServer ();
    }
    m_Ref = -1;
    ShowStatus ();
    EnableDlgItem (IDC_OPEN);
    EnableDlgItem (IDC_CLOSE, FALSE);
    EnableDlgItem (IDC_GET_STATUS, FALSE);
    EnableDlgItem (IDC_RXDATA, FALSE);
    EnableDlgItem (IDC_TXDATA, FALSE);
    EnableDlgItem (IDC_CONNECT, FALSE);
  }
	
}

void CRFC1006DemoDlg::OnConnect() 
{
	if (m_Ref >= 0)
  {
    UpdateData (TRUE);
    Rfc1006Connect (m_Ref);
    ShowStatus ();
  }
}

void CRFC1006DemoDlg::OnGetStatus() 
{
	if (m_Ref >= 0)
  {
    if (Rfc1006GetStatus (m_Ref) == 1)
    {
      ShowStatus ("verbunden / connected");
    }
    else
    {
			if (Rfc1006GetSockErr(m_Ref))
			{
        ShowStatus (E_RFC1006_SOCKERR);				
			}
			else
			{
			  ShowStatus ("nicht verbunden / not connected");
			}
    }
  }
  else
    ShowStatus ("Verbindung geschlossen / connection closed");
}



void CRFC1006DemoDlg::OnTxData() 
{
  static int BlockNr;
  int TxCnt;
  long Res;
	if (m_Ref >= 0 && UpdateData (TRUE))
  {
    TxCnt = m_strTxData.GetLength ();
    Res = Rfc1006Tx (m_Ref, (void *)((const char *)m_strTxData), TxCnt, 0);

    if (Res == TxCnt)
    {
      ShowStatus ("Daten gesendet / data sent");
    }
    else
    {
      ShowStatus (Res);
    }
  }
}

void
DumpData (CString &Dst, void *vblock,  int length)
{

  int i,j;
  char linebuf[256]; // TEST static
  char *lp;
  BYTE *block = (BYTE * )vblock;

  Dst = "";
  for (i = 0; i < length; i += 16)
  {
    for (j = 0; (j < 16) && (j+i < length); j++)
    {
      sprintf (linebuf + 3 * j,"%02x ",block[i+j]);
    }
   
    for (;j < 16;)
    {
      strcat (linebuf, "   ");
      ++j;
    }

    linebuf[3*j]='\0';

    lp = &linebuf[strlen(linebuf)];
    
    for (j=0; (j < 16) && (j+i < length); j++)
    {
      sprintf (lp + j,"%c",isprint (block[i+j]) ?block[i+j]:'.');
    }
    lp[j++]='\r';
    lp[j]='\0';
    Dst = Dst + (const char *)linebuf;
  }
}



void CRFC1006DemoDlg::OnRxData() 
{
	if (m_Ref >= 0)
  {
    int RLen;
    RLen = Rfc1006Rx (m_Ref, (void *)((const char *)m_RxData), sizeof (m_RxData) - 1, m_RxTimeout);
    if (RLen > 0)
    {
      m_RxData[RLen] = 0;
//      m_strRxData = (const char *) m_RxData;
      DumpData (m_strRxData, m_RxData, RLen);
      ((CEdit*)GetDlgItem(IDC_DATARECEIVED))->SetWindowText ((const char *)m_strRxData);
    }
    else
    {
      ShowStatus ();
    }
  }
}

void CRFC1006DemoDlg::EnableDlgItem(int DlgId, BOOL bEnable)
{
  ((CButton*)GetDlgItem(DlgId))->EnableWindow (bEnable);
}


//void CRFC1006DemoDlg::OnTimer(UINT nIDEvent) 
void CRFC1006DemoDlg::OnTimer(UINT_PTR nIDEvent) 
{
  if (m_Ref >= 0)
  {
    if (Rfc1006GetStatus (m_Ref) == 1)
    {
      int RLen = 0;
      int Cnt = 0;
      ShowStatus ("verbunden / connected");
      do
      {
				if (Rfc1006PacketInQ (m_Ref))
				{
					RLen = Rfc1006Rx (m_Ref, (void *)((const char *)m_RxData), sizeof (m_RxData) - 1, m_RxTimeout);
					if (RLen > 0)
					{
						m_RxData[RLen] = 0;
		//      m_strRxData = (const char *) m_RxData;
						DumpData (m_strRxData, m_RxData, RLen);
						((CEdit*)GetDlgItem(IDC_DATARECEIVED))->SetWindowText ((const char *)m_strRxData);
						ShowStatus ("Daten empfangen / data received");
					}
				}
      } while (++Cnt < 10 && RLen > 0);
    }
    else
    {
      ShowStatus ("nicht verbunden / not connected");
    }
  }
	CDialog::OnTimer(nIDEvent);
}

BOOL CRFC1006DemoDlg::DestroyWindow() 
{
	// TODO: Add your specialized code here and/or call the base class
	KillTimer (1);
	
	return CDialog::DestroyWindow();
}

void CRFC1006DemoDlg::ShowStatus(const char *Text)
{
  ((CEdit*)GetDlgItem(IDC_STATUS))->SetWindowText (Text);
}

void CRFC1006DemoDlg::ShowStatus(int Res)
{
  CString S;
  int SocketErr;

  switch (Res)
  {
    case E_RFC1006_TIMEOUT:
      S = "Zeitueberlauf / Timeout";
      break;
    
    case E_RFC1006_NORES_AVAIL:
      S = "keine Resourcen mehr frei. / No more resources available.";
      break;

    case E_RFC1006_REF_NOTOPENED:
      S = "Mit der angegebenen Ref-Nr. wurde kein Rfc1006Openxxx aufgerufen. /"
        "Passed RefNo wasn't init with call to Rfc1006Openxxx";
      break;
    
    case E_RFC1006_GENERAL:
      S = "allgemeiner Fehler / general error";
      break;
    
    case E_RFC1006_NOPARTNER:
      SocketErr = Rfc1006GetSockErr (m_Ref);
      S.Format ("Partner nicht gefunden. / Can't find partner. SocketError:%d", SocketErr);
      break;
    
    case E_RFC1006_SOCKERR:
      SocketErr = Rfc1006GetSockErr (m_Ref);
      char StrSockErr [1024];
     
      Rfc1006GetSockErrString(SocketErr, StrSockErr, sizeof (StrSockErr));
      S.Format ("Socket-Fehler / Socket Error:%d : %s", SocketErr,StrSockErr );
      break;
    
    case E_RFC1006_SERVER_YET_RUNNING:
      S = "Server ist bereits gestartet. / Server is running yet.";
      break;
    
    case E_RFC1006_STARTING_SERVER:
      S = "Server kann nicht gestartet werden. / Server couldn't be started.";
      break;


    case E_RFC1006_SERVER_NOT_RUNNING:
      S = "Server war nicht gestartet. / Server was not running.";
      break;
    
    case E_RFC1006_NOCONNECTION:
      S = "Noch kein Client mit Server verbunden. / No client yet connected to server.";
      break;

    case -1234:
    case 0x1234:
      S = "Demozeit ist abgelaufen / demo time has expired";
      break;
    
    default:   
      S = "Fehlernummer siehe Handbuch / For error code see manual";
  }                               
  ((CEdit*)GetDlgItem(IDC_STATUS))->SetWindowText (S);
}

void CRFC1006DemoDlg::ShowStatus()
{
  OnGetStatus ();
}


void CRFC1006DemoDlg::OnSrcTSAPHex() 
{
   if (m_ctrlSrcTSAPHex.GetCheck ())
     m_ctrlSrcTSAP.SetDataMode (CHexEditCtrl::HEX_MODE);
   else
     m_ctrlSrcTSAP.SetDataMode (CHexEditCtrl::TEXT_MODE);
}

void CRFC1006DemoDlg::OnDstSAPHex() 
{
   if (m_ctrlDstTSAPHex.GetCheck ())
     m_ctrlDstTSAP.SetDataMode (CHexEditCtrl::HEX_MODE);
   else
     m_ctrlDstTSAP.SetDataMode (CHexEditCtrl::TEXT_MODE);
}

void CRFC1006DemoDlg::OnTxDataHex() 
{
  if (m_ctrlTxDataHex.GetCheck ())
   m_ctrlTxData.SetDataMode (CHexEditCtrl::HEX_MODE);
  else
   m_ctrlTxData.SetDataMode (CHexEditCtrl::TEXT_MODE);
}

void CRFC1006DemoDlg::OnRxDataHex() 
{
  if (m_ctrlRxDataHex.GetCheck ())
   m_ctrlRxData.SetDataMode (CHexEditCtrl::HEX_MODE);
  else
   m_ctrlRxData.SetDataMode (CHexEditCtrl::TEXT_MODE);
}
