MFC消息映射

 

 

 

 

 


// EcrSimulatorDlg.h : header file

#pragma once
#include "DigTab_Conn.h"
#include "Diglog_COM.h"
#include <paxnet/EventLoop.h>
#include <thread>
#include "EcrConnection.h"
#include "SerialConnection.h"
#include "Diglog_EMV.h"
#include "Diglog_CMD.h"
#include <paxnet/PclRequestMessage.h>
#include "PXProxy\PXUpdaterProxyClient.h"
#include "Diglog_SHOW.h"
#include "Diglog_Extra.h"
#include <paxnet/PclResponseMessage.h>
#include "MfcSocket.h"
//#include "ClientDlg.h"

// CEcrSimulatorDlg dialog
class CEcrSimulatorDlg : public CDialogEx
{
// Construction
public:
	CEcrSimulatorDlg(CWnd* pParent = NULL);	// standard constructor

// Dialog Data
	enum { IDD = IDD_ECRSIMULATOR_DIALOG };

protected:
	virtual void DoDataExchange(CDataExchange* pDX);	// DDX/DDV support
	

// Implementation
protected:
	typedef enum
	{
		TCPIP = 0,
		COMM,
		MFC_SOCKET
	}CONNETION_TYPE;
	HICON m_hIcon;
	CTabCtrl m_tablist;
	CTabCtrl m_tablistCMD;
	//connection 
	CDigTab_Conn m_dlgtab_conn;
	CDiglog_COM m_dlgtab_com;
	
	CONNETION_TYPE m_pageShow;
	//CMD
	CDiglog_SHOW m_dlgtale_show;//add
	CDiglog_EMV m_dlgEmv;
	CDiglog_CMD m_dlgCmd;
	CDiglog_Extra m_dlgtable_extra;//add
	MfcSocket m_dlgtable_socket;//add
	// Generated message map functions
	virtual BOOL OnInitDialog();
	afx_msg void OnPaint();//afx_msg 暗示为一个消息处理程序
	afx_msg HCURSOR OnQueryDragIcon();
	DECLARE_MESSAGE_MAP()//声明消息映射
public:
	afx_msg void OnTcnSelchangeTabMenu(NMHDR *pNMHDR, LRESULT *pResult);
	afx_msg void OnTcnSelchangeCMD(NMHDR *pNMHDR, LRESULT *pResult);
	afx_msg void OnBnClickedButtonCon();
	afx_msg void OnBnClickedButtonSend();

private:
	pax::EventLoop m_pEventLoop;
	int show_wnd;
	EcrConnection tcpClient_;
	SerialConnection serialClient_;
	bool m_bTcpConnected;
	bool m_bSerlConnected;
	std::thread *thread_eventLoop;
	void loop();
	void endcontactless();
	bool bLoopAlive;
    std::shared_ptr<PXUpdaterProxyClient> chsClient_;
    std::shared_ptr<PXUpdaterProxyClient> adsClient_;
    std::shared_ptr<PXUpdaterProxyClient> hmsClient_;
    pax::DataBuffer inputBuffer_;
    pax::DataBuffer inputTlvMessage_;
    pax::PclResponseMessage response_;

 // CString strData;
 
public:
	void setSendBuffer(const void * buffer, size_t bufSize);
	void setRecvBuffer(const void * buffer, size_t bufSize);
	void dumpSend(int nID,const void * buffer, size_t n);
	void dumpRecv(int nID,const void * buffer, size_t n);
	void tcpConnect();
	void serialConnect();
    bool receiveMessage();
    void handleMessage(const void* buffer, size_t bufSize, pax::TlvMessage& msg);
    void setResponseMessage(pax::PclResponseMessage response);
    void dump_cb(int nID, const void * buffer, size_t n);

    CDiglog_SHOW *getShow();
    CDiglog_Extra*getExtra();
    void setConnectStatus();
    void setDisconnectStatus();
private:
    void DoTheTransation(pax::PclResponseMessage response);
    void WicRelease();
    void OnTest2(int nID, CString str);

};

// EcrSimulatorDlg.cpp : implementation file
//

#include "stdafx.h"
#include "EcrSimulator.h"
#include "EcrSimulatorDlg.h"
#include "afxdialogex.h"
#include "EcrClientSimApp.h"
#include <paxnet\PclEmvDetectICCardCommand.h>
#include <paxnet\PclEmvBeginContactTxnCommand.h>
#include <paxnet\PclEmvContinueContactTxnCommand.h>
#include <paxnet\PclEmvEndContactTxnCommand.h>
#include <paxnet\PclEmvBeginContactlessTxnCommand.h>
#include <paxnet\PclEmvEndContactlessTxnCommand.h>
#include <paxnet\PclEmvRemoveContactCardCommand.h>
#include <paxnet\PclEmvSetContactTLVDataCommand.h>
#include <paxnet\PclEmvSetContactlessTLVDataCommand.h>
#include <paxnet\PclEmvGetContactTLVDataCommand.h>
#include <paxnet\PclEmvGetContactlessTLVDataCommand.h>
#include <paxnet\PclEmvReleaseContactlessServiceCommand.h>
#include <paxnet\PclDisplayFormCommand.h>
#include <paxnet\PclSetFormPackageCommand.h>
#include <paxnet\PclGetPackageListCommand.h>
#include <paxnet\PclGetVariableListCommand.h>
#include <paxnet\PclSetVariableCommand.h>
#include <paxnet\PclGetFormListCommand.h>
#include <paxnet\DataBuffer.h>
#include <paxnet\PclDownloadResult.h>
#include <paxnet\PclResponseMessage.h>
#include <paxnet\PclGetFileCommand.h>
#include <paxnet\PclEmvGetAppListContactTxnCommand.h>
#include <paxnet\PclEmvSelectAppContactTxnCommand.h>
#include <paxnet\PclGetVariableCommand.h>
#include <paxnet\PclWicClaimServiceCommand.h>
#include <paxnet\PclWicExchangeWMPCommand.h>
#include <paxnet\PclWicReleaseServiceCommand.h>

#include<ctime>
#include<cstdlib>

#include "Cdiglogpublic.h"
#include "ResponseQueue.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define EMV_PAGE                        0
#define SHOW_PAGE                       0
#define CMD_PAGE                        1
#define EMV_PAGE                        2
#define EXTRA_PAGE                      3
#define MFC_SOCKET                      4

#define EMVDETECTICCARD					0
#define EMVBEGIN					    1
#define EMVGETAPPLIST		            2
#define EMVSELECTAPP                    3
#define EMVCONTINUE						4
#define EMVSETCONTACTTLVDATA		    5
#define EMVGETCONTACTTLVDATA			6
#define EMVCOMPLETE						7
#define EMVREMOVECARD		            8
#define EMVCLSSBEGIN					9
#define EMVCLSSEND						10
#define EMVSETCONTACTLESSTLVDATA		11
#define EMVGETCONTACTLESSTLVDATA		12
#define EMVCONTACTLESSRELEASESERVICE    13

// CEcrSimulatorDlg dialog

#define DISPLAYFORM             0
#define SETFORMPACKAGE          1
#define GETPACKAGELIST          2
#define GETVARIABLELIST         3
#define SETVARIABLE             4
#define GETVARIABLE 			5
#define GETFILE                 6
#define GETFORMLIST		        7



CEcrSimulatorDlg::CEcrSimulatorDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CEcrSimulatorDlg::IDD, pParent),
  serialClient_(&m_pEventLoop)//,
 // strData("")
{
  chsClient_ = std::make_shared<PXUpdaterProxyClient>();
  adsClient_ = std::make_shared<PXUpdaterProxyClient>();
  hmsClient_ = std::make_shared<PXUpdaterProxyClient>();
	m_hIcon = AfxGetApp()->LoadIcon(IDI_PAX);
	m_bTcpConnected = false;
	m_bSerlConnected = false;
	bLoopAlive = false;
}

CDiglog_SHOW* CEcrSimulatorDlg::getShow(){
	return &m_dlgtale_show;
}
CDiglog_Extra* CEcrSimulatorDlg::getExtra(){
	return &m_dlgtable_extra;
}


void CEcrSimulatorDlg::DoDataExchange(CDataExchange* pDX)
{
	DDX_Control(pDX, IDC_TAB_MENU, m_tablist);
	DDX_Control(pDX, IDC_CMD, m_tablistCMD);
	CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CEcrSimulatorDlg, CDialogEx)//通过放置标志消息的宏来执行消息映射
	ON_WM_PAINT()    //头文件afxmsg.h 中定义的宏
	ON_WM_QUERYDRAGICON()
	ON_NOTIFY(TCN_SELCHANGE, IDC_TAB_MENU, &CEcrSimulatorDlg::OnTcnSelchangeTabMenu)
	ON_NOTIFY(TCN_SELCHANGE, IDC_CMD, &CEcrSimulatorDlg::OnTcnSelchangeCMD)//添加消息成员函数来处理消息
	ON_BN_CLICKED(IDC_BUTTON_CON, &CEcrSimulatorDlg::OnBnClickedButtonCon)
	ON_BN_CLICKED(IDC_BUTTON_SEND, &CEcrSimulatorDlg::OnBnClickedButtonSend)
END_MESSAGE_MAP()


// CEcrSimulatorDlg message handlers

BOOL CEcrSimulatorDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();
	//pax::Application test;
	// 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

	CString title="TTR v1.00.05";//要修改的标题
	this->SetWindowText(title);

	//CMenu menu;
	//menu.LoadMenu(IDR_MENU1);  //IDR_MENU1为菜单栏ID号
	//SetMenu(&menu);

	// TODO: Add extra initialization here
	//pax::Application test;
	m_tablist.InsertItem(0, _T("TCP"));
	m_tablist.InsertItem(1, _T("COM"));
	//m_tablist.InsertItem(2, _T("MFC_SOCKET"));

	m_tablistCMD.InsertItem(0, _T("TRANS"));
	m_tablistCMD.InsertItem(1, _T("CMD"));
	m_tablistCMD.InsertItem(2, _T("EMV"));
	m_tablistCMD.InsertItem(3, _T("EXTRA"));
	m_tablistCMD.InsertItem(4, _T("ANY_DATA"));
	
	
	CDiglog_SHOW::setDialog(this);
	m_dlgtale_show.Create(IDD_SHOW, &m_tablistCMD);
	m_dlgCmd.Create(IDD_CMD, &m_tablistCMD);
	m_dlgEmv.Create(IDD_EMV, &m_tablistCMD);
	m_dlgtable_extra.Create(IDD_EXTRA, &m_tablistCMD);
	m_dlgtable_socket.Create(IDD_MFCSOCKET, &m_tablistCMD);

	
	m_dlgtab_conn.Create(IDD_TCP, &m_tablist);
	m_dlgtab_com.Create(IDD_COM, &m_tablist);
	//m_dlgtable_socket.Create(IDD_MFCSOCKET, &m_tablist);
	m_dlgtable_socket.setDialog(&m_dlgtab_conn);

	m_dlgtab_com.InitCtrl();

	CString ip;
	auto ret = GetPrivateProfileStringA("Config", "ipAddress", "", ip.GetBuffer(20), 20, strConfigFile.c_str());
	if (ret > 0)
	{
		m_dlgtab_conn.SetIPAddress(ip);
	}
	else
	{
		m_dlgtab_conn.SetIPAddress("172.16.20.0");
	}
		
	
	m_dlgtab_conn.SetPort("1235");
	CRect rc;
	m_tablist.GetClientRect(rc);
	rc.top += 21;
	rc.bottom -= 1;
	rc.left += 1;
	rc.right -= 1;
	m_dlgtab_conn.MoveWindow(rc);
	m_dlgtab_com.MoveWindow(rc);
	
	m_dlgtab_conn.ShowWindow(SW_SHOW);
	m_dlgtab_com.ShowWindow(SW_HIDE);
	
	m_pageShow = TCPIP;
	m_tablist.SetCurSel(m_pageShow);

	CRect rc_cmd;
	m_tablistCMD.GetClientRect(rc_cmd);
	rc_cmd.top += 21;
	rc_cmd.bottom -= 1;
	rc_cmd.left += 1;
	rc_cmd.right -= 1;
	m_dlgEmv.MoveWindow(rc_cmd);
	m_dlgCmd.MoveWindow(rc_cmd);
	m_dlgtale_show.MoveWindow(rc_cmd);
	m_dlgtable_extra.MoveWindow(rc_cmd);
	m_dlgtable_socket.MoveWindow(rc_cmd);
	
	m_dlgCmd.ShowWindow(SW_HIDE);
	m_dlgEmv.ShowWindow(SW_HIDE);
	m_dlgtale_show.ShowWindow(SW_SHOW);
	m_dlgtable_extra.ShowWindow(SW_HIDE);
	m_dlgtable_socket.ShowWindow(SW_HIDE);
	
	//show_wnd = EMV_PAGE;
	show_wnd = SHOW_PAGE;
  	chsClient_->setChannel(0);
  	chsClient_->setHostAddress("52.23.117.203");
  	chsClient_->setHostPort(444);
  	//chsClient_->setEcrConnection(&tcpClient_);
  	chsClient_->setSerialConnection(&serialClient_);

  	adsClient_->setChannel(1);
  	adsClient_->setHostAddress("52.23.117.203");
  	adsClient_->setHostPort(444);
  	//adsClient_->setEcrConnection(&tcpClient_);
  	adsClient_->setSerialConnection(&serialClient_);

  	if (!adsClient_->connectToHost())
  	{
    	return TRUE;
  	}

  	hmsClient_->setChannel(2);
  	hmsClient_->setHostAddress("52.23.117.203");
  	hmsClient_->setHostPort(444);
  	//hmsClient_->setEcrConnection(&tcpClient_);
  	hmsClient_->setSerialConnection(&serialClient_);
 
  	m_pEventLoop.addDevice(chsClient_.get());
  	m_pEventLoop.addDevice(adsClient_.get());
  	m_pEventLoop.addDevice(hmsClient_.get());

    m_dlgtale_show.EnableWindow(FALSE);
    m_dlgEmv.EnableWindow(FALSE);
    m_dlgCmd.EnableWindow(FALSE);
    m_dlgtable_extra.EnableWindow(FALSE);

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

// 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 CEcrSimulatorDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<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
	{
		CDialogEx::OnPaint();
	}
}

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



void CEcrSimulatorDlg::OnTcnSelchangeTabMenu(NMHDR *pNMHDR, LRESULT *pResult)
{
	// TODO:  在此添加控件通知处理程序代码
	m_pageShow = (CONNETION_TYPE)m_tablist.GetCurSel();
	if (m_pageShow == TCPIP)
	{
		m_dlgtab_conn.ShowWindow(SW_SHOW);
		m_dlgtab_com.ShowWindow(SW_HIDE);
		m_pageShow = TCPIP;
	}
	else 
	{
		m_dlgtab_conn.ShowWindow(SW_HIDE);
		m_dlgtab_com.ShowWindow(SW_SHOW);
		m_pageShow = COMM;
		
	}

	*pResult = 0;
}

void CEcrSimulatorDlg::OnTcnSelchangeCMD(NMHDR *pNMHDR, LRESULT *pResult)
{
	show_wnd = m_tablistCMD.GetCurSel();
	CButton *pEndBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_SEND);
	pEndBtn->EnableWindow(true);
	pEndBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_CON);
	pEndBtn->EnableWindow(true);
	m_dlgtale_show.EnableWindow(true);
	m_dlgEmv.EnableWindow(true);
	m_dlgCmd.EnableWindow(true);
	m_dlgtable_extra.EnableWindow(true);
		
	if (show_wnd == CMD_PAGE)
	{
		m_dlgCmd.ShowWindow(SW_SHOW);//显示CMD页面
		m_dlgEmv.ShowWindow(SW_HIDE);//隐藏EMV 页面
		m_dlgtale_show.ShowWindow(SW_HIDE);
		m_dlgtable_extra.ShowWindow(SW_HIDE);
		m_dlgtable_socket.ShowWindow(SW_HIDE);
		show_wnd = CMD_PAGE;
	}
	else if(show_wnd == EMV_PAGE)
	{
		m_dlgEmv.ShowWindow(SW_SHOW);
		m_dlgtale_show.ShowWindow(SW_HIDE);
		m_dlgCmd.ShowWindow(SW_HIDE);
		m_dlgtable_extra.ShowWindow(SW_HIDE);
		m_dlgtable_socket.ShowWindow(SW_HIDE);
		show_wnd = EMV_PAGE;
	}else if (show_wnd == SHOW_PAGE)
	{
		m_dlgtale_show.ShowWindow(SW_SHOW);
		m_dlgCmd.ShowWindow(SW_HIDE);
		m_dlgEmv.ShowWindow(SW_HIDE);
		m_dlgtable_extra.ShowWindow(SW_HIDE);
		m_dlgtable_socket.ShowWindow(SW_HIDE);
		show_wnd = SHOW_PAGE;
	}else if (show_wnd == EXTRA_PAGE)
	{
		m_dlgtable_extra.ShowWindow(SW_SHOW);
		m_dlgtale_show.ShowWindow(SW_HIDE);
		m_dlgCmd.ShowWindow(SW_HIDE);
		m_dlgEmv.ShowWindow(SW_HIDE);
		m_dlgtable_socket.ShowWindow(SW_HIDE);
		show_wnd = EXTRA_PAGE;
	}else{
		m_dlgtable_socket.ShowWindow(SW_SHOW);
		m_dlgtable_extra.ShowWindow(SW_HIDE);
		m_dlgtale_show.ShowWindow(SW_HIDE);
		m_dlgCmd.ShowWindow(SW_HIDE);
		m_dlgEmv.ShowWindow(SW_HIDE);
		show_wnd = MFC_SOCKET;

        m_tablist.EnableWindow(FALSE);
	    //m_tablistCMD.EnableWindow(FALSE);
	    CButton *pEndBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_SEND);
		pEndBtn->EnableWindow(false);
		pEndBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_CON);
		pEndBtn->EnableWindow(false);
	    m_dlgtale_show.EnableWindow(FALSE);
	    m_dlgEmv.EnableWindow(FALSE);
	    m_dlgCmd.EnableWindow(FALSE);
	    m_dlgtable_extra.EnableWindow(FALSE);
	}
	*pResult = 0;
}

void CEcrSimulatorDlg::loop()
{
	while (bLoopAlive)
	{
		m_pEventLoop.processEvents(100);
		if (m_pageShow == TCPIP)
		{
			if (tcpClient_.getState() == EcrConnection::ClosedState)
			{
				break;
			}
		}
		else
		{
			if (serialClient_.getState() == SerialConnection::ClosedState)
			{
				break;
			}
		}	
	}
}
void CEcrSimulatorDlg::OnBnClickedButtonCon()//按键connect
{
  CString state;

	if (m_pageShow == TCPIP)
	{
		tcpConnect();
		m_dlgtale_show.setConnct(true);
		m_dlgtable_extra.setConnct(true);
	}
	else
	{
		serialConnect();
		m_dlgtale_show.setConnct(false);
		m_dlgtable_extra.setConnct(false);
	}
	#if 1
  GetDlgItemText(IDC_BUTTON_CON, state);
  if (state == "disconnect")//is connected
  {
		m_tablist.EnableWindow(FALSE);
		// m_tablistCMD.EnableWindow(TRUE);
		m_dlgtale_show.EnableWindow(TRUE);
		m_dlgEmv.EnableWindow(TRUE);
		m_dlgCmd.EnableWindow(TRUE);
		m_dlgtable_extra.EnableWindow(TRUE);
  }
  else
  {
    m_tablist.EnableWindow(TRUE);
	//m_tablistCMD.EnableWindow(FALSE);
	m_dlgtale_show.EnableWindow(FALSE);
	m_dlgEmv.EnableWindow(FALSE);
	m_dlgCmd.EnableWindow(FALSE);
	m_dlgtable_extra.EnableWindow(FALSE);
  }
  #endif
}
void CEcrSimulatorDlg::setConnectStatus(){
	CString strIP, strPort,title,state;
	m_dlgtab_conn.GetDlgItemText(IDC_IPADDRESS, strIP);
	m_dlgtab_conn.GetDlgItemText(IDC_PORT, strPort);
	SetDlgItemText(IDC_BUTTON_CON, "disconnect");
	CButton *pSendBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_SEND);
	pSendBtn->EnableWindow(true);
	m_bTcpConnected = true;
	
	title="TTR v1.00.05 [IP Address-" + strIP + " PortNumber-" + strPort + "] [connected] for pax internal use only";//要修改的标题
	this->SetWindowText(title);
    m_tablist.EnableWindow(FALSE);
    m_tablistCMD.EnableWindow(TRUE);

}
void CEcrSimulatorDlg::setDisconnectStatus(){
	CString title;
	SetDlgItemText(IDC_BUTTON_CON, "connect");
	CButton *pSendBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_SEND);
	pSendBtn->EnableWindow(false);
	m_bTcpConnected = false;
	title="TTR v1.00.05 [disconnect] for pax internal use only";//要修改的标题
	this->SetWindowText(title);

	m_tablist.EnableWindow(TRUE);
	m_tablistCMD.EnableWindow(FALSE);
}

void CEcrSimulatorDlg::tcpConnect()
{
	// TODO:  在此添加控件通知处理程序代码
	CString strIP, strPort,title;
	int i = -1;
	m_dlgtab_conn.GetDlgItemText(IDC_IPADDRESS, strIP);
	m_dlgtab_conn.GetDlgItemText(IDC_PORT, strPort);
	WritePrivateProfileString("Config", "ipAddress", strIP, strConfigFile.c_str());
    tcpClient_.setProtocol();
	if (!m_bTcpConnected)
	{
		//WritePrivateProfileString("Config", "ipAddress", strIP, strConfigFile.c_str());

		tcpClient_.setHostAddress(strIP.GetBuffer(0));
		tcpClient_.setHostPort(atoi(strPort));
		tcpClient_.setDialog(this);
		if (!tcpClient_.connectToHost())
		{
			// Could not initiate a connection (probably a configuration error).
			return;
		}

		//if( tcpClient_.isClosed() ) return;
		//if (tcpClient_.isClosing()) return;
		i = tcpClient_.getState();
		
		if (i == EcrConnection::ClosedState){
			return;
		}

	#if	1
		SetDlgItemText(IDC_BUTTON_CON, "disconnect");
		CButton *pSendBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_SEND);
		pSendBtn->EnableWindow(true);
		m_bTcpConnected = true;
		
		title="TTR v1.00.05 [IP Address-" + strIP + " PortNumber-" + strPort + "] [connected] for pax internal use only";//要修改的标题
		this->SetWindowText(title);
	#endif

	
		m_pEventLoop.addDevice(&tcpClient_);
        bLoopAlive = true;
		thread_eventLoop = new std::thread(&CEcrSimulatorDlg::loop, this);

		m_dlgtale_show.addTcpDev(&tcpClient_);
		m_dlgtable_extra.addTcpDev(&tcpClient_);
		m_dlgCmd.addTcpDev(&tcpClient_);
		 
		title="TTR v1.00.05 [IP Address-" + strIP + " PortNumber-" + strPort + "] [connected] for pax internal use only";//要修改的标题
		this->SetWindowText(title);
	}
	else
	{
			
		tcpClient_.setDialog(nullptr);
		bLoopAlive = false;
		thread_eventLoop->join();
		m_pEventLoop.removeDevice(&tcpClient_);
		tcpClient_.close();
		#if 1
		SetDlgItemText(IDC_BUTTON_CON, "connect");
		CButton *pSendBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_SEND);
		pSendBtn->EnableWindow(false);
		m_bTcpConnected = false;
		title="TTR v1.00.05 [disconnect] for pax internal use only";//要修改的标题
		this->SetWindowText(title);
		#endif
		//add
		//m_tablist.EnableWindow(TRUE);
		//m_tablistCMD.EnableWindow(FALSE);
		//pSendBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_SEND);
	   // pSendBtn->EnableWindow(false);
	}
}

void CEcrSimulatorDlg::serialConnect()
{
  CString strCOM, strBuad,title;
  pax::SerialPort::BaudRate baudrate ;
  m_dlgtab_com.GetDlgItemText(IDC_COMBO_COM, strCOM);
  m_dlgtab_com.GetDlgItemText(IDC_COMBO_BAUD, strBuad);
  if (strBuad == "115200")
  {
    baudrate = pax::SerialPort::BaudRate::SERIAL_BAUD_RATE_115200;
  }
  else if (strBuad == "57600")
  {
    baudrate = pax::SerialPort::BaudRate::SERIAL_BAUD_RATE_57600;
  }
  else if (strBuad == "38400")
  {
    baudrate = pax::SerialPort::BaudRate::SERIAL_BAUD_RATE_38400;
  }
  else if (strBuad == "19200")
  {
    baudrate = pax::SerialPort::BaudRate::SERIAL_BAUD_RATE_19200;
  }
  else if (strBuad == "9600")
  {
    baudrate = pax::SerialPort::BaudRate::SERIAL_BAUD_RATE_9600;
  }
  else
  {
    baudrate = pax::SerialPort::BaudRate::SERIAL_BAUD_RATE_115200;
  }
	if (!m_bSerlConnected)
	{  
    	serialClient_.setPortName(strCOM.GetBuffer(0));
		serialClient_.setDialog(this);
		// attempt to open the device
		if (!serialClient_.open())
		{	
			return;
		}
    	serialClient_.setBaudRate(baudrate);
		serialClient_.setDataBits(pax::SerialPort::DataBits::SERIAL_DATA_BITS_8);
		serialClient_.setParity(pax::SerialPort::Parity::SERIAL_PARITY_NONE);
		serialClient_.setStopBits(pax::SerialPort::StopBits::SERIAL_STOP_BITS_1);
		serialClient_.setFlowControl(pax::SerialPort::FlowControl::SERIAL_FLOW_CONTROL_NONE);
		serialClient_.setDTR(0);
		serialClient_.setCTS(0);
		serialClient_.setRTS(0);

		// commit the serial port configuration changes
		serialClient_.activateConfiguration();
		
		if (serialClient_.getState() == SerialConnection::ClosedState){
			return;
		}
		
		SetDlgItemText(IDC_BUTTON_CON, "disconnect");
		CButton *pSendBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_SEND);
		pSendBtn->EnableWindow(true);
		
		m_bSerlConnected = true;
		m_pEventLoop.addDevice(&serialClient_);
		bLoopAlive = true;
		thread_eventLoop = new std::thread(&CEcrSimulatorDlg::loop, this);
		//add 
		m_dlgtale_show.addSerialDev(&serialClient_);
		m_dlgtable_extra.addSerialDev(&serialClient_);
		m_dlgCmd.addSerialDev(&serialClient_);
		
		title="TTR v1.00.05 [COM-" + strCOM + "] [connected] for pax internal use only";//要修改的标题
		this->SetWindowText(title);
		
	}
	else
	{
		serialClient_.setDialog(nullptr);
		bLoopAlive = false;
		thread_eventLoop->join();
		m_pEventLoop.removeDevice(&serialClient_);
		serialClient_.close();
		SetDlgItemText(IDC_BUTTON_CON, "connect");
		CButton *pSendBtn = (CButton*)this->GetDlgItem(IDC_BUTTON_SEND);
		pSendBtn->EnableWindow(false);
		m_bSerlConnected = false;
		
		title="TTR v1.00.05 [disconnect] for pax internal use only";//要修改的标题
		this->SetWindowText(title);
	}
}


void CEcrSimulatorDlg::OnBnClickedButtonSend()//按键send
{
	// TODO:  在此添加控件通知处理程序代码
	//app.
	
	pax::PclRequestMessage request;

	// source
	auto sourceAddress = "ECR";
	request.setSourceAddress(sourceAddress);

	// destination
	auto destAddress = "TERMINAL";
	request.setDestAddress(destAddress);
	
	// Process I/O events until we receive the response or fail.
	if (show_wnd == EMV_PAGE)
	{
		
		CComboBox *comboEMVCMD = (CComboBox*)m_dlgEmv.GetDlgItem(IDC_COMBOEMV);//下拉框
		CEdit *pEditFormName = (CEdit*)m_dlgEmv.GetDlgItem(IDC_FORMNAME);
		int iclientType = m_dlgEmv.getClientType();
		int emvCMD_type = comboEMVCMD->GetCurSel();
		
		//ACI mode
		if(iclientType == 1){
			switch(emvCMD_type){
				case 0:
				{
					pax::PclEmvDetectICCardCommand detectCMD;
					detectCMD.setSequenceNo(0);
					detectCMD.addToMessage(request);
				}
					break;
				case 1:
				{
	        		pax::PclEmvGetAppListContactTxnCommand getAppListCMD;
					std::vector<pax::EMV_TLV> emv_datas;
					if (!m_dlgEmv.GetEMVData(emv_datas))
						//return;
					getAppListCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
	        		getAppListCMD.setSequenceNo(0);
	        		getAppListCMD.addToMessage(request);
			     }
			        break;
				case 2:
				{
	        		pax::PclEmvSelectAppContactTxnCommand selecttAppCMD;
					std::vector<pax::EMV_TLV> emv_datas;
					if (!m_dlgEmv.GetEMVData(emv_datas))
						//return;
					selecttAppCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
	        		selecttAppCMD.setSequenceNo(0);
	       	 		selecttAppCMD.addToMessage(request);
		       }
		        	break;
				case 3:
				{
					pax::PclEmvContinueContactTxnCommand continueCMD;
					std::vector<pax::EMV_TLV> emv_datas;
					m_dlgEmv.GetEMVData(emv_datas);
					CString strFormName;
					pEditFormName->GetWindowText(strFormName);
					continueCMD.setFormName(strFormName.GetBuffer());
					continueCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
					continueCMD.setSequenceNo(0);
					continueCMD.addToMessage(request);
				}
					break;
				case 4:
				{
					pax::PclEmvEndContactTxnCommand endCMD;
					std::vector<pax::EMV_TLV> emv_datas;
					if (!m_dlgEmv.GetEMVData(emv_datas))
						//return;
					endCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
					endCMD.setSequenceNo(0);
					endCMD.addToMessage(request);
				}
					break;
				case 5:
				{
					pax::PclEmvRemoveContactCardCommand removecardCMD;
					removecardCMD.setSequenceNo(0);
					removecardCMD.addToMessage(request);
				}
					break;
				case 6:
				{
					
					pax::PclEmvBeginContactlessTxnCommand beginclessCMD;
					std::vector<pax::EMV_TLV> emv_datas;
					if (!m_dlgEmv.GetEMVData(emv_datas))
						//return;
					beginclessCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
					beginclessCMD.setSequenceNo(0);
					beginclessCMD.addToMessage(request);

				}
					break;
				case 7:
				{
					pax::PclEmvEndContactlessTxnCommand endclessCMD;
					std::vector<pax::EMV_TLV> emv_datas;
					if (!m_dlgEmv.GetEMVData(emv_datas))
						//return;
					endclessCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
					endclessCMD.setSequenceNo(0);
					endclessCMD.addToMessage(request);
				}
					break;
				case 8:
				{
			        pax::PclEmvReleaseContactlessServiceCommand releaseCMD;
			        releaseCMD.setSequenceNo(0);
			        releaseCMD.addToMessage(request);
		        } 
	                break;
				default:
					break;
			}
		}
		else if(iclientType == 2){
			switch(emvCMD_type){
			 case 0:
			 {
				 pax::PclEmvDetectICCardCommand detectCMD;
				 detectCMD.setSequenceNo(0);
				 detectCMD.addToMessage(request);
			 }
				 break;
			 case 1:
			 {
				 pax::PclEmvBeginContactTxnCommand beginCMD;
				 std::vector<pax::EMV_TLV> emv_datas;
				 m_dlgEmv.GetEMVData(emv_datas);//从列表框中获取EMV数据
				 beginCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
				 beginCMD.setSequenceNo(0);
				 beginCMD.addToMessage(request);
			  }
				 break;
			 
			 case 2:
			 {
				 pax::PclEmvContinueContactTxnCommand continueCMD;
				 std::vector<pax::EMV_TLV> emv_datas;
				 m_dlgEmv.GetEMVData(emv_datas);
				 CString strFormName;
				 pEditFormName->GetWindowText(strFormName);
				 continueCMD.setFormName(strFormName.GetBuffer());
				 continueCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
				 continueCMD.setSequenceNo(0);
				 continueCMD.addToMessage(request);
			 }
				 break;
			 case 3:
			 {
				 pax::PclEmvEndContactTxnCommand endCMD;
				 std::vector<pax::EMV_TLV> emv_datas;
				 m_dlgEmv.GetEMVData(emv_datas);
				 endCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
				 endCMD.setSequenceNo(0);
				 endCMD.addToMessage(request);
			 }
				 break;
			 case 4:
			 {
				 pax::PclEmvRemoveContactCardCommand removecardCMD;
				 removecardCMD.setSequenceNo(0);
				 removecardCMD.addToMessage(request);
			 }
				 break;
			 case 5:
			 {
				 pax::PclEmvBeginContactlessTxnCommand beginclessCMD;
				 std::vector<pax::EMV_TLV> emv_datas;
				 m_dlgEmv.GetEMVData(emv_datas);
				 beginclessCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
				 beginclessCMD.setSequenceNo(0);
				 beginclessCMD.addToMessage(request);
			
			 }
				 break;
			 case 6:
			 {
				 pax::PclEmvEndContactlessTxnCommand endclessCMD;
				 std::vector<pax::EMV_TLV> emv_datas;
				 m_dlgEmv.GetEMVData(emv_datas);
				 endclessCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
				 endclessCMD.setSequenceNo(0);
				 endclessCMD.addToMessage(request);
			 }
				 break;
			 case 7:
			 {
				 pax::PclEmvReleaseContactlessServiceCommand releaseCMD;
				 releaseCMD.setSequenceNo(0);
				 releaseCMD.addToMessage(request);
			 } 
				 break;
			 default:
				 break;
			}
		}
		else if(iclientType == 3){
			//HEB mode
			switch(emvCMD_type){
				case 0:
				{
					pax::PclWicClaimServiceCommand CMD;
					std::vector<pax::EMV_TLV> emv_datas;
					m_dlgEmv.GetEMVData(emv_datas);
					pax::EMV_TLV tlv = emv_datas.front();
					//std::string str = tlv.strTag+tlv.strData+tlv.strKer;
					std::string str = tlv.strData;
					pax::DataBuffer dataTLV(1024);
					dataTLV.insertData(str.c_str(), str.size());
					CMD.setWICKeyIndex(dataTLV);
					CMD.setSequenceNo(0);
					CMD.addToMessage(request);
				}
					break;
				case 1:
				{
					 pax::PclWicExchangeWMPCommand ExchangeWMPCMD;
					 std::vector<pax::EMV_TLV> emv_datas;
					 m_dlgEmv.GetEMVData(emv_datas);
					 pax::EMV_TLV tlv = emv_datas.front();
					 //std::string str = tlv.strTag+tlv.strData+tlv.strKer;
					 std::string str = tlv.strData;
					 pax::DataBuffer dataTLV(1024);
					 dataTLV.insertData(str.c_str(), str.size());
					 ExchangeWMPCMD.setWMPData(dataTLV);
					 ExchangeWMPCMD.setSequenceNo(0);
					 ExchangeWMPCMD.addToMessage(request);
				}
				case 2:
				{
					pax::PclWicReleaseServiceCommand cmd;
					cmd.setSequenceNo(0);
					cmd.addToMessage(request);
				}
			}
		}
		else if(iclientType == 4){
			switch (emvCMD_type){
				case 0:
				{
					pax::PclEmvSetContactTLVDataCommand setTLVDataCMD;
					std::vector<pax::EMV_TLV> emv_datas;
					m_dlgEmv.GetEMVData(emv_datas);
					setTLVDataCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
					setTLVDataCMD.setSequenceNo(0);
					setTLVDataCMD.addToMessage(request);
				}
					break;
				case 1:
				{
					pax::PclEmvGetContactTLVDataCommand getTLVDataCMD;
					std::vector<pax::EMV_TLV> emv_datas;
					m_dlgEmv.GetEMVData(emv_datas);
					getTLVDataCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
					getTLVDataCMD.setSequenceNo(0);
					getTLVDataCMD.addToMessage(request);
				}
					break;
				case 2:
				{
					pax::PclEmvSetContactlessTLVDataCommand setTLVDataCMD;
					std::vector<pax::EMV_TLV> emv_datas;
					m_dlgEmv.GetEMVData(emv_datas);
					setTLVDataCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
					setTLVDataCMD.setSequenceNo(0);
					setTLVDataCMD.addToMessage(request);
				}
					break;
				case 3:
				{
					pax::PclEmvGetContactlessTLVDataCommand getTLVDataCMD;
					std::vector<pax::EMV_TLV> emv_datas;
					m_dlgEmv.GetEMVData(emv_datas);
					getTLVDataCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
					getTLVDataCMD.setSequenceNo(0);
					getTLVDataCMD.addToMessage(request);
				}
					break;
				default:
					break;
			}
		}
	}
	else if (show_wnd == CMD_PAGE)
	{
		CComboBox *comboCMD = (CComboBox*)m_dlgCmd.GetDlgItem(IDC_COMBOCMD);
		CEdit *pEditFormName = (CEdit*)m_dlgCmd.GetDlgItem(IDC_EDIT4);
	    CEdit *pEditName = (CEdit*)m_dlgCmd.GetDlgItem(IDC_EDIT1);
	    CEdit *pEditValue = (CEdit*)m_dlgCmd.GetDlgItem(IDC_EDIT2);

		int CMD_type = comboCMD->GetCurSel();
	    switch (CMD_type)
	    {
	    case DISPLAYFORM:
	    {
		      pax::PclDisplayFormCommand displayCMD;
		      CString strFormName;
		      pEditFormName->GetWindowText(strFormName);
		      displayCMD.setFormName(strFormName.GetBuffer());
		      displayCMD.setSequenceNo(0);
		      displayCMD.addToMessage(request);
	    }
	      break;
	    case SETFORMPACKAGE:
	    {
             pax::PclSetFormPackageCommand setPkgCMD;
             CString strPkgName;
             pEditFormName->GetWindowText(strPkgName);
             setPkgCMD.setPackageName(strPkgName.GetBuffer());
             setPkgCMD.setSequenceNo(0);
             setPkgCMD.addToMessage(request);
	    }
	      break;
	    case GETPACKAGELIST:
	    {
             pax::PclGetPackageListCommand getPkgCMD;
             getPkgCMD.setSequenceNo(0);
             getPkgCMD.addToMessage(request);
		}
	      break;
	    case GETVARIABLELIST:
	    {
              pax::PclGetVariableListCommand getVarListCMD;
              getVarListCMD.setSequenceNo(0);
              getVarListCMD.addToMessage(request);
	    }
	      break;

    case GETFORMLIST:
    {
		pax::PclGetFormListCommand getFormListCMD;
        getFormListCMD.setSequenceNo(0);
        getFormListCMD.addToMessage(request);
    }
        break;
		case GETVARIABLE:
    {
		pax::PclGetVariableCommand getVarCMD;
		CString strName;
        pEditName->GetWindowText(strName);
		getVarCMD.addVariable(std::string(strName.GetBuffer()));
        getVarCMD.setSequenceNo(0);
        getVarCMD.addToMessage(request);
    }
        break;
		case GETFILE:
    {
		pax::PclGetFileCommand getFileCMD;
		CString fileName;
        pEditName->GetWindowText(fileName);
		getFileCMD.setFileName(std::string(fileName.GetBuffer()));
		getFileCMD.setStartOffset(0);
		getFileCMD.setEndOffset(3*1024);
        getFileCMD.setSequenceNo(0);
        getFileCMD.addToMessage(request);
    }
        break;
      
	    case SETVARIABLE:
	    {
		#if 0
			  CString IP, Port;
              CEdit *pEditIP = (CEdit*)m_dlgCmd.GetDlgItem(IDC_EDIT6);
              CEdit *pEditPort = (CEdit*)m_dlgCmd.GetDlgItem(IDC_EDIT5);
              pEditIP->GetWindowText(IP);
              pEditPort->GetWindowText(Port);
        #endif
              pax::PclSetVariableCommand setVarCMD;
              setVarCMD.setSequenceNo(0);
              CString strName,strValue;
              pEditName->GetWindowText(strName);
              pEditValue->GetWindowText(strValue);
              pax::KeyValueMap keyValueMap = { { std::string(strName.GetBuffer()), std::string(strValue.GetBuffer()) } };
              setVarCMD.setVariables(keyValueMap);
              setVarCMD.addToMessage(request);
	    }
	      break;
	    }
	}
	else if (show_wnd == EXTRA_PAGE)
	{
		//pax::TlvMessage msg;
		pax::PclRequestMessage msg;
		pax::DataBuffer buffer;
		
		CString strSendData;
		CEdit *pSend = (CEdit*)m_dlgtable_extra.GetDlgItem(IDC_SEND_MESSAGE);
		pSend->GetWindowText(strSendData);
	    std::string str = std::string(strSendData.GetBuffer());

#define TEST
#ifdef TEST
		if(!m_dlgtable_extra.getSendTlvMessage(str, request, buffer)){
			return;
		}
#else

		uint16_t TlvDataLen = 0;
		bool ret=false;
		pax::PclRequestMessage req;
		unsigned char pData[MAX_SIZE]={0};
		m_dlgtable_extra.Asc2Bcd((const uchar*)str.c_str(), str.length(), pData);
		int icharDateLen = (str.length())/2;
		//buffer = pax::DataBuffer(icharDateLen);
		//buffer.insertData(pData, icharDateLen);
		
		if (m_pageShow == TCPIP){
			//unsigned char Data[MAX_SIZE]={0};
			//int i = buffer.extractData( Data, 1024);
			tcpClient_.sendBufferMessage(pData, icharDateLen);
		}else{
			//serialClient_.sendBufferMessage(buffer);
		}
		return;
#endif
	}
	
	if (m_pageShow == TCPIP)
	{
		tcpClient_.sendRequest(request);
	}
	else
	{
		serialClient_.sendRequest(request);
	}
}

#define SizeLine 32

void CEcrSimulatorDlg::dumpRecv(int nID, const void * buffer, size_t n)
{
	strDataRecv="";
	char textBuffer[SizeLine * 3 + 6 + SizeLine + 1];
	const char * pSrc = reinterpret_cast<const char *>(buffer);
	size_t i;

	while (n)
	{
		const char * p = pSrc;

		char * pHex = &textBuffer[0];
		char * pAscii = &textBuffer[SizeLine * 3 + 6];
		for (i = 0; i < n && i < SizeLine; ++i, ++p)
		{
			sprintf_s(pHex, sizeof(textBuffer)-i * 3, " %02X ", (unsigned int)(*p & 0x00FF));
			pHex += 3;

			unsigned char ch = *p;
			if (ch < 0x20 || ch >= 0x7F)
			{
				ch = '.';
			}
			*pAscii++ = ch;
		}

		pSrc += i;
		n -= i;
#if 1
		while (i++ < SizeLine)
		{
			sprintf_s(pHex, sizeof(textBuffer)-i * 3, "   ");

			pHex += 3;
			*pAscii++ = ' ';
		}
#endif

		*pHex++ = ' ';
		*pHex++ = ' ';
		*pHex++ = ' ';
		*pHex++ = ' ';
		*pHex++ = ' ';
		*pHex++ = ' ';
		*pAscii = '\0';

		strDataRecv += textBuffer;
		strDataRecv += "\r\n";
		
	}
	strDataRecv += "\r\n";
	//strDataRecv += "\r\n";
#if 0
	if (show_wnd == EMV_PAGE)
	{
		m_dlgEmv.SetDlgItemText(nID, strDataRecv);
	}
	else if(show_wnd == CMD_PAGE)
	{
		m_dlgCmd.SetDlgItemText(nID, strDataRecv);
	}
	else if(show_wnd == EXTRA_PAGE)
	{
		m_dlgtable_extra.SetDlgItemText(nID, strDataRecv);
	}
	else if(show_wnd == SHOW_PAGE)
	{
		m_dlgtale_show.SetDlgItemText(nID, strDataRecv);
	}
#endif
	OnTest2(nID,strDataRecv);
}
void CEcrSimulatorDlg::dumpSend(int nID, const void * buffer, size_t n)
{	
	strDataSend="";
	char textBuffer[SizeLine * 3 + 6 + SizeLine + 1];
	const char * pSrc = reinterpret_cast<const char *>(buffer);
	size_t i;

	while (n)
	{
		const char * p = pSrc;

		char * pHex = &textBuffer[0];
		char * pAscii = &textBuffer[SizeLine * 3 + 6];
		for (i = 0; i < n && i < SizeLine; ++i, ++p)
		{
			sprintf_s(pHex, sizeof(textBuffer)-i * 3, " %02X ", (unsigned int)(*p & 0x00FF));
			pHex += 3;

			unsigned char ch = *p;
			if (ch < 0x20 || ch >= 0x7F)
			{
				ch = '.';
			}
			*pAscii++ = ch;
		}

		pSrc += i;
		n -= i;
#if 1
		while (i++ < SizeLine)
		{
			sprintf_s(pHex, sizeof(textBuffer)-i * 3, "   ");

			pHex += 3;
			*pAscii++ = ' ';
		}
#endif

		*pHex++ = ' ';
		*pHex++ = ' ';
		*pHex++ = ' ';
		*pHex++ = ' ';
		*pHex++ = ' ';
		*pHex++ = ' ';
		*pAscii = '\0';

		strDataSend += textBuffer;
		strDataSend += "\r\n";
		
	}
	strDataSend += "\r\n";
	//strDataSend += "\r\n";
#if 0
	if (show_wnd == EMV_PAGE)
	{
		m_dlgEmv.SetDlgItemText(nID, strDataSend);
	}
	else if(show_wnd == CMD_PAGE)
	{
		m_dlgCmd.SetDlgItemText(nID, strDataSend);
	}
	else if(show_wnd == EXTRA_PAGE)
	{
		m_dlgtable_extra.SetDlgItemText(nID, strDataSend);
	}
	else if(show_wnd == SHOW_PAGE)
	{
		m_dlgtale_show.SetDlgItemText(nID, strDataSend);
	}
#endif
	OnTest2(nID,strDataSend);
}

void CEcrSimulatorDlg::OnTest2(int nID, CString str)
{	
	CEdit *pEdit;
	if (show_wnd == EMV_PAGE)
	{
		pEdit  = (CEdit*)m_dlgEmv.GetDlgItem(nID);
	}
	else if(show_wnd == CMD_PAGE)
	{
		pEdit  = (CEdit*)m_dlgCmd.GetDlgItem(nID);
	}
	else if(show_wnd == EXTRA_PAGE)
	{
		m_dlgtable_extra.SetDlgItemText(nID,str);
	}
	else if(show_wnd == SHOW_PAGE)
	{
		pEdit  = (CEdit*)m_dlgtale_show.GetDlgItem(nID);
	}
	
	if(show_wnd != EXTRA_PAGE){
		
	int nLength = pEdit->GetWindowTextLength();
	//选定当前文本的末端
    pEdit->SetSel(nLength, nLength);
	 //追加文本
    pEdit->ReplaceSel(_T(str));
	}
}
#if 0

void CEcrSimulatorDlg::dump(int nID, const void * buffer, size_t n)
{
	CString strData = "";
	char textBuffer[16 * 3 + 2 + 16 + 1];
	const char * pSrc = reinterpret_cast<const char *>(buffer);
	size_t i;

	while (n)
	{
		const char * p = pSrc;

		char * pHex = &textBuffer[0];
		char * pAscii = &textBuffer[16 * 3 + 2];
		for (i = 0; i < n && i < 16; ++i, ++p)
		{
			sprintf_s(pHex, sizeof(textBuffer)-i * 3, " %02X ", (unsigned int)(*p & 0x00FF));
			pHex += 3;

			unsigned char ch = *p;
			if (ch < 0x20 || ch >= 0x7F)
			{
				ch = '.';
			}
			*pAscii++ = ch;
		}

		pSrc += i;
		n -= i;

		while (i++ < 16)
		{
			sprintf_s(pHex, sizeof(textBuffer)-i * 3, "   ");

			pHex += 3;
			*pAscii++ = ' ';
		}
		*pHex++ = ' ';
		*pHex++ = ' ';
		*pAscii = '\0';

		strData += textBuffer;
		strData += "\r\n";
		
	}
	if (show_wnd == EMV_PAGE)
	{
		m_dlgEmv.SetDlgItemText(nID, strData);
	}
	else
	{
		m_dlgCmd.SetDlgItemText(nID, strData);
	}
	
}


#define size 16
void CEcrSimulatorDlg::dump_cb(int nID, const void * buffer, size_t n)
{
	CString strData = "";
	char textBuffer[size * 3 + 2 + size + 1];
	const char * pSrc = reinterpret_cast<const char *>(buffer);
	size_t i;

	while (n)
	{
		const char * p = pSrc;

		char * pHex = &textBuffer[0];
		char * pAscii = &textBuffer[ size * 3 + 2];
		for (i = 0; i < n && i < size; ++i, ++p)
		{
			sprintf_s(pHex, sizeof(textBuffer)-i * 3, " %02X ", (unsigned int)(*p & 0x00FF));
			pHex += 3;

			unsigned char ch = *p;
			if (ch < 0x20 || ch >= 0x7F)
			{
				ch = '.';
			}
			*pAscii++ = ch;
		}

		pSrc += i;
		n -= i;

		while (i++ < size)
		{
			sprintf_s(pHex, sizeof(textBuffer)-i * 3, "  ");

			pHex += 3;
			*pAscii++ = ' ';
		}
		*pHex++ = '   ';
		*pHex++ = '   ';
		*pAscii = '\0';

		strData += textBuffer;
		strData += "\r\n";
		
	}
	if (show_wnd == EMV_PAGE)
	{
		m_dlgEmv.SetDlgItemText(nID, strData);
	}
	else if(show_wnd == CMD_PAGE)
	{
		m_dlgCmd.SetDlgItemText(nID, strData);
	}
	else if(show_wnd == EXTRA_PAGE)
	{
		m_dlgtable_extra.SetDlgItemText(nID, strData);
	}
	else if(show_wnd == SHOW_PAGE)
	{
		m_dlgtale_show.SetDlgItemText(nID, strData);
	}
}
#endif
void CEcrSimulatorDlg::setSendBuffer(const void * buffer, size_t bufSize)
{
	dumpSend(IDC_EDITSEND, buffer, bufSize);//显示数据在send发送栏里
}


bool CEcrSimulatorDlg::receiveMessage()
{
  const void * pData = inputBuffer_.getExtractionPointer();
  size_t recvLen = inputBuffer_.getExtractableCount();
  const uint8_t * p = reinterpret_cast<const uint8_t *>(pData);
  const char * pbuffStart = reinterpret_cast<char *>(inputBuffer_.getExtractionPointer());
  uint16_t dataLen = 0;
  uint32_t msgLen = 0;

  // We can't parse anything until we've received at least 3 bytes,
  // 1 byte for the STX and 2 bytes for the data length.
  if (recvLen < 3)
  {
    return false;
  }

  // First byte should be an STX character.
  if (*p++ != 0x02)
  {

    return false;
  }

  // The next two bytes are the length of the message data.
  dataLen += *p++;
  dataLen <<= 8;
  dataLen += *p++;

  // The total message length is the data length plus 8:
  // 1 for STX, 2 for data length, 1 for ETX, and 4 for the CRC.
  msgLen = dataLen + 8;

  // Wait until we have received the entire message before parsing it.
  if (recvLen < msgLen)
  {
    return false;
  }

  // Save a pointer to the start of the message data, then advance the
  // parsing pointer beyond the message data.  We need to verify that
  // the message has a valid ETX and CRC before we process the message
  // content.
  bool validMessage = true;
  const uint8_t * pMsgData = p;
  p += dataLen;

  // Verify that an ETX character immediately follows the message data.
  if (*p++ != 0x03)
  {
    validMessage = false;
  }

  // Parse and validate the CRC only if the messge is considered valid so far.
  //if (validMessage)
  //{
    // The next four bytes are the CRC.
    // Validate the CRC.
    //char calculatedcrc[4] = { 0 };
   // CRC::CalculateCRC(pbuffStart, dataLen + 4, calculatedcrc);//calculate crc from STX to ETX

    // Currently we also allow the CRC to be all zeros.  This is needed for
    // backward compatibility with older applications that do not compute the
    // real CRC.  Eventually, this support for a CRC of all zeros must be
    // removed.    
    //if (memcmp(calculatedcrc, p, 4) != 0 &&
    //  memcmp("\x00\x00\x00\x00", p, 4) != 0)
    //{
    //  validMessage = false;
    //}
  //}

  // If the message is valid, then save the TLV message content.
  if (validMessage)
  {
    inputTlvMessage_ = pax::DataBuffer(dataLen);
    inputTlvMessage_.insertData(pMsgData, dataLen);
  }

  // Remove the message from the buffer.
  inputBuffer_.extractedData(msgLen);

  // Indicate that we received a complete message.
  return true;
}

void CEcrSimulatorDlg::handleMessage(const void* buffer, size_t bufSize, pax::TlvMessage& msg)
{
  for (;;)
  {
    if (!receiveMessage())
    {
      return ;
    }
    auto ret = msg.parse(inputTlvMessage_);
    if (!ret) return;
  }
  
  
}

void CEcrSimulatorDlg::setResponseMessage(pax::PclResponseMessage response){
	//CdiglogPublic::m_Mutex.lock();
	//response_ = response;
	if (show_wnd == EMV_PAGE)
	{
		//pDiglog = m_dlgEmv;
	}
	else if(show_wnd == CMD_PAGE)
	{
		//pDiglog = m_dlgCmd;
	}
	else if(show_wnd == EXTRA_PAGE)
	{
		//m_dlgtable_extra.setResponseMsg(&response_);
	}
	else if(show_wnd == SHOW_PAGE)
	{
		//m_dlgtale_show.setResponseMsg(&response_);
	}
	//CdiglogPublic::setResponseList(response);
	//CdiglogPublic::m_Mutex.unlock();
}


void CEcrSimulatorDlg::DoTheTransation(pax::PclResponseMessage response){
	
	if(!m_dlgtale_show.getNotify()){
		//return;
	}
	if(show_wnd != SHOW_PAGE){
		m_dlgtale_show.setNotify();
		return;
	}

	std::shared_ptr< pax::PclResult > result = response.getResult(0);
  	auto resultCode = result->getResultCode();
	auto type = result->getCommandType();
	
	//begin contactless card response
	if(type == pax::PclCommandBase::ENUM_PCLCOMMAND::EMV_BEGIN_CONTACTLESS_TXN){
		if(resultCode == 0){
			m_dlgtale_show.AddAndShowRFTimes(1);//调用一个接口成功加一
			CDiglog_SHOW::m_RFCardMutex.lock();
			bBeginSuccsess = true;
			CDiglog_SHOW::m_RFCardMutex.unlock();
		}
		if(!m_dlgtale_show.getApproved()) return endcontactless();
		pax::PclEmvEndContactlessTxnCommand endclessCMD;
		std::vector<pax::EMV_TLV> emv_datas;
		m_dlgtale_show.GetINIEmvData("Contactless","END", emv_datas);
		endclessCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
		endclessCMD.setSequenceNo(0);
		m_dlgtale_show.setCommandRequest(&endclessCMD);
		return;
		//}
		//else
		//{
			//return endcontactless();
		//}
	}
	else if (type == pax::PclCommandBase::ENUM_PCLCOMMAND::EMV_END_CONTACTLESS_TXN){
		return endcontactless();
	}
	
	//EMVDetectICCard contact response
	else if ((type == pax::PclCommandBase::ENUM_PCLCOMMAND::EMV_DETECT_ICCARD)){
		
		if(resultCode == 0)
		{
			CDiglog_SHOW::m_ICCardMutex.lock();
			bDetectSuccess = true;
			CDiglog_SHOW::m_ICCardMutex.unlock();

			m_dlgtale_show.AddAndShowICTimes(1);//调用一个接口成功加一
			
			if(m_dlgtale_show.IsAciMod() == 1)
			{
				pax::PclEmvGetAppListContactTxnCommand getAppListCMD;
				std::vector<pax::EMV_TLV> emv_datas;
				m_dlgtale_show.GetINIEmvData("Contact","GETAPPLIST", emv_datas);
				getAppListCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
				getAppListCMD.setSequenceNo(0);
				m_dlgtale_show.setCommandRequest(&getAppListCMD);

			}
			else{
				pax::PclEmvBeginContactTxnCommand beginCMD;
				std::vector<pax::EMV_TLV> emv_datas;
				m_dlgtale_show.GetINIEmvData("Contact","BEGIN", emv_datas);
				beginCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
				beginCMD.setSequenceNo(0);
				m_dlgtale_show.setCommandRequest(&beginCMD);
			}
			//a command is processed then return back
			return;
		}else{
			//DetectICCard error, so remove card
			goto removeCard;
		}
	 }
	else if(type == pax::PclCommandBase::ENUM_PCLCOMMAND::EMV_GETAPPLIST_CONTACT_TXN){
		if(resultCode == 0)
		{
			pax::PclEmvSelectAppContactTxnCommand selecttAppCMD;
			std::vector<pax::EMV_TLV> emv_datas;
			m_dlgtale_show.GetINIEmvData("Contact","SELECTAPP", emv_datas);
			selecttAppCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
			selecttAppCMD.setSequenceNo(0);
			m_dlgtale_show.setCommandRequest(&selecttAppCMD);

			return;//return wait for the Continue command

		}else{
			goto removeCard;
		}

	}
	else if((type == pax::PclCommandBase::ENUM_PCLCOMMAND::EMV_BEGIN_CONTACT_TXN)
		||(type == pax::PclCommandBase::ENUM_PCLCOMMAND::EMV_SELECTAPP_CONTACT_TXN))
	{
		if(resultCode == 0)
		{
			//when selectapped or begincontact is retun ok, 
			pax::PclEmvContinueContactTxnCommand continueCMD;
			std::vector<pax::EMV_TLV> emv_data;
			CString buffer;
			GetPrivateProfileStringA("Config", "FormName", "", buffer.GetBuffer(50), 50, strConfigFile.c_str());
			continueCMD.setFormName(buffer.GetBuffer());
			m_dlgtale_show.GetINIEmvData("Contact","CONTINUE", emv_data);
			continueCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_data));
			continueCMD.setSequenceNo(0);
			m_dlgtale_show.setCommandRequest(&continueCMD);

			return;//then send the continue command and return back.
			
		}else{
			goto removeCard;

		}
	}
	else if(type == pax::PclCommandBase::ENUM_PCLCOMMAND::EMV_CONTINUE_CONTACT_TXN){
		if(resultCode == 0){
			pax::PclEmvEndContactTxnCommand endCMD;
			std::vector<pax::EMV_TLV> emv_datas;
			m_dlgtale_show.GetINIEmvData("Contact","END", emv_datas);
			endCMD.addEMVTLVData(std::make_shared<std::vector<pax::EMV_TLV>>(emv_datas));
			endCMD.setSequenceNo(0);
			m_dlgtale_show.setCommandRequest(&endCMD);
			return;

		}else{
			goto removeCard;
		}
	}
	else if(type == pax::PclCommandBase::ENUM_PCLCOMMAND::EMV_END_CONTACT_TXN){
		goto removeCard;
	}
	
	else if(type == pax::PclCommandBase::ENUM_PCLCOMMAND::WIC_CLAIM_SERVICE){
		// for WIC services
		if(resultCode == 0){
			 CDiglog_SHOW::m_WicMutex.lock();
			 bWicSuccess = true;
			 CDiglog_SHOW::m_WicMutex.unlock();
			 
			 m_dlgtale_show.AddAndShowICTimes(1);//调用第一次接口成功了加一
			 
			 pax::PclWicExchangeWMPCommand ExchangeWMPCMD;
			 std::vector<pax::EMV_TLV> emv_datas;
			 m_dlgtale_show.GetINIEmvData("WIC","ExchangeWMP", emv_datas);
			 pax::EMV_TLV tlv = emv_datas.front();
			 std::string str = tlv.strData;
			 pax::DataBuffer dataTLV(1024);
			 dataTLV.insertData(str.c_str(), str.size());
			 ExchangeWMPCMD.setWMPData(dataTLV);
			 ExchangeWMPCMD.setSequenceNo(0);
			 m_dlgtale_show.setCommandRequest(&ExchangeWMPCMD);
			 return;
		}else{
			
			return WicRelease();
		}
	}
	
	else if(type == pax::PclCommandBase::ENUM_PCLCOMMAND::WIC_EXCHANGE_WMP){
		return WicRelease();
	}
	//add for put file command
	else if(type == pax::PclCommandBase::ENUM_PCLCOMMAND::PUT_FILE){
		P_RESPONSEQUEUE->putResponse(response);
		return;
	}
	else{ //the other commands
		m_dlgtale_show.setNotify();

		//CdiglogPublic::m_Mutex.lock();
		//bDetectSuccess = false;
		//bBeginSuccsess = false;
		//CdiglogPublic::m_Mutex.unlock();
		return;
	}

removeCard: 	

	pax::PclEmvRemoveContactCardCommand removecardCMD;
	removecardCMD.setSequenceNo(0);
	m_dlgtale_show.setCommandRequest(&removecardCMD);

	CDiglog_SHOW::m_ICCardMutex.lock();
	bDetectSuccess = false;
	CDiglog_SHOW::m_ICCardMutex.unlock();
	
	m_dlgtale_show.setNotify();
	return;
}
void CEcrSimulatorDlg::WicRelease(){
	pax::PclWicReleaseServiceCommand cmd;
	cmd.setSequenceNo(0);
	m_dlgtale_show.setCommandRequest(&cmd);
	CDiglog_SHOW::m_WicMutex.lock();
	bWicSuccess = false;
	CDiglog_SHOW::m_WicMutex.unlock();
	return;
}
void CEcrSimulatorDlg::endcontactless(){
	
	pax::PclEmvReleaseContactlessServiceCommand releaseCMD;
	releaseCMD.setSequenceNo(0);
	m_dlgtale_show.setCommandRequest(&releaseCMD);

	CDiglog_SHOW::m_RFCardMutex.lock();
	bBeginSuccsess = false;
	CDiglog_SHOW::m_RFCardMutex.unlock();

	m_dlgtale_show.setNotify();//a contactless transation is end

	return;
}
#if 0
#include <fiostream.h>

void CEcrSimulatorDlg:: WriteLog () {
	 ofstream out("out.txt");
	 if (out.is_open()) 
	{
		 out << "This is a line.\n";
		 out << "This is another line.\n";
		 out.close();
	 }
	 return 0;
 }
#endif
	 
void CEcrSimulatorDlg::setRecvBuffer(const void * buffer, size_t bufSize)
{
	dumpRecv(IDC_EDITRECV, buffer, bufSize);//显示数据在接收栏中

  if (inputBuffer_.getExtractableCount() > 0)
  {
    size_t combinedSize = inputBuffer_.getExtractableCount() + bufSize;
    pax::DataBuffer combinedBuffer(combinedSize);
    combinedBuffer.insertData(inputBuffer_.getExtractionPointer(),
      inputBuffer_.getExtractableCount());
    combinedBuffer.insertData(buffer,bufSize);

    // The new commbined buffer becomes the input buffer.
    inputBuffer_ = combinedBuffer;
  }
  else // Input buffer is empty
  {
    pax::DataBuffer nextBuffer(bufSize);
    nextBuffer.insertData(buffer,bufSize);
    // The new buffer becomes the input buffer.
    inputBuffer_ = nextBuffer;
  }
  pax::PclResponseMessage response;
  handleMessage(buffer, bufSize,response);
  
  if (response.getResultCount() <= 0)
  {
    inputBuffer_.extractedData(bufSize);
    return;
  }
  
  //setResponseMessage(response);
  DoTheTransation(response);
  
  std::shared_ptr< pax::PclResult > result = response.getResult(0);
  auto type = result->getCommandType();
  if (type == pax::PclCommandBase::ENUM_PCLCOMMAND::DOWNLOAD)
  {
    std::shared_ptr< pax::PclDownloadResult> downResult = std::static_pointer_cast< pax::PclDownloadResult >(result);
    pax::DataBuffer downloadBuffer;
    downResult->getMessage(downloadBuffer);
    auto channel = downResult->getMessageChannel();
    if (channel == 0)
    {
      if (!chsClient_->isClosed())
      {
        chsClient_->close();
      }

      if (!chsClient_->connectToHost())
      {
        return;
      }
      chsClient_->sendRequest(downloadBuffer);
    }
    else if (channel == 1)
    {
      adsClient_->sendRequest(downloadBuffer);
    }
    else if (channel == 2)
    {
      if (!hmsClient_->isClosed())
      {
        hmsClient_->close();
      }

      if (!hmsClient_->connectToHost())
      {
        return;
      }
      hmsClient_->sendRequest(downloadBuffer);
    }
  }
  
  //
  //result.
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值