// ZLG600DLL_TESTDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ZLG600DLL_TEST.h"
#include "ZLG600DLL_TESTDlg.h"
#include "ZLG600_DLL.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define CBR_28800           28800
unsigned char ModulFormat= 0;   //模块通信帧格式，0--旧帧格式  1---新帧格式
//全局变量定义
unsigned char AuthFlag=0;                //记录某一扇区密钥验证是否通过
unsigned char CurSector=0;               //记录当前选中的扇区号
unsigned char SectorFlag=200;             //记录上一次选中的扇区号
unsigned char UID[10];                   //用于存放卡片ID号
unsigned char WriteBuff[16],ReadBuff[16];//定义读写缓冲区
UCHAR  ATQA[2],SAK;
UCHAR   AddrBuff[]={0xB0,0xB2,0xB4,0xB6,0xB8};   //地址编号
//============= 外部变量定义 ====================================================================================
extern unsigned char     Format;              //新旧帧格式标记  1：新帧   0：旧帧
extern unsigned char     LocallAddr;          //模块地址
extern unsigned char     SlotIndex;           //卡槽索引
extern unsigned char     SMCSeq;              //数据帧包号

/////////////////////////////////////////////////////////////////////////////
int Str2Hex(const char* str, unsigned char* data);
char HexChar(unsigned char c);
// CAboutDlg dialog used for App About
/************************************************************************
****将一个十六进制的字符串（str），转化为一个字符数组（data）
****改函数要调用下面HexChar
****返回值：转化后字符串有效数据长度
***************************************************************************/
int Str2Hex(const char* str, unsigned char* data)
{
	int t, t1;
	int rlen = 0, len = strlen(str);
	for (int i = 0; i < len;)
	{
		char l, h = str[i];
		if (h == ' '|| h == ':')  //如果有空格或者冒号
		{
			i++;
			continue;
		}
		i++;
		if(i >= len) break;
		l = str[i];
		t = HexChar(h);			//h一字节中的高位
		t1 = HexChar(l);		//l一字节中的低位
		// data[rlen] = t*10+t1;
		if((t == 16)||(t1 == 16))
			break;
		else
			t = t*16+t1;
		i++;
		data[rlen]=t;  /** 如果写成char(t)则只能表示0到127的ASII字符，
					   大于128的字符都表示不了，所以不加char，直接用数字表
					   
		示*/
		rlen++;
	}
	return rlen;
}

char HexChar(unsigned char c)
{
	if((c>='0')&&(c<='9'))
		return c-0x30;
	else if((c>='A')&&(c<='F'))
		return c-'A'+10;    //加10是为了符合十六进制的要求
	else if((c>='a')&&(c<='f'))
		return c-'a'+10;
	else
		return 0x10;
}

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()

/////////////////////////////////////////////////////////////////////////////
// CZLG600DLL_TESTDlg dialog

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

void CZLG600DLL_TESTDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CZLG600DLL_TESTDlg)
	DDX_Control(pDX, IDC_COMBO_NowAddr, m_CNowAddr);
	DDX_Control(pDX, IDC_COMBO_ADDR, m_NewADDR);
	DDX_Control(pDX, IDC_COMBO_ComuModel, m_cMode);
	DDX_Control(pDX, IDC_EDIT_NowAddr, m_NowAddr);
	DDX_Control(pDX, IDC_COMBO_NowFormat, m_NowFormat);
	DDX_Control(pDX, IDC_EDIT_Addr, m_Addr);
	DDX_Control(pDX, IDC_COMBO_Format, m_Format);
	DDX_Control(pDX, IDC_COMBO1_UARTBDR, m_UARTBDR);
	DDX_Control(pDX, IDC_COMBO2_BDR, m_uartBdr);
	DDX_Control(pDX, IDC_COMBO1_UART, m_uartNum);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CZLG600DLL_TESTDlg, CDialog)
	//{{AFX_MSG_MAP(CZLG600DLL_TESTDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1_Open, OnBUTTON1Open)
	ON_BN_CLICKED(IDC_BUTTON2_Close, OnBUTTON2Close)
	ON_BN_CLICKED(IDC_BUTTON_SetBDR, OnBUTTONSetBDR)
	ON_CBN_SELCHANGE(IDC_COMBO_Format, OnSelchangeCOMBOFormat)
	ON_EN_CHANGE(IDC_EDIT_Addr, OnChangeEDITAddr)
	ON_CBN_SELCHANGE(IDC_COMBO_NowFormat, OnSelchangeCOMBONowFormat)
	ON_EN_CHANGE(IDC_EDIT_NowAddr, OnChangeEDITNowAddr)
	ON_CBN_SELENDCANCEL(IDC_COMBO_NowFormat, OnSelendcancelCOMBONowFormat)
	ON_CBN_EDITCHANGE(IDC_COMBO_NowAddr, OnEditchangeCOMBONowAddr)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CZLG600DLL_TESTDlg message handlers

BOOL CZLG600DLL_TESTDlg::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
	m_uartBdr.SetCurSel(1);
	m_uartNum.SetCurSel(1);

	m_UARTBDR.SetCurSel(1);
	m_Format.SetCurSel(0);
	m_NowFormat.SetCurSel(0);
	GetDlgItem(IDC_COMBO_NowAddr)->EnableWindow(FALSE);//旧帧格式时，关闭地址选项
	
	GetDlgItem(IDC_BUTTON2_Close)->EnableWindow(FALSE);
	memset(WriteBuff,0,16);
	memset(ReadBuff,0,16);

	unsigned char ucTemp[] = {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff};
	
	

	m_Addr.SetMaxDataLen(1);
	m_Addr.SetEndian(TRUE);
	m_Addr.SetData(&LocallAddr,1);

	m_NewADDR.SetCurSel(1);//默认选择B2

	m_NowAddr.SetMaxDataLen(1);
	m_NowAddr.SetEndian(TRUE);
	m_NowAddr.SetData(&LocallAddr,1);
	m_CNowAddr.SetCurSel(1);
	m_cMode.SetCurSel(2);
	
	UpdateData(FALSE);
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CZLG600DLL_TESTDlg::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 CZLG600DLL_TESTDlg::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 CZLG600DLL_TESTDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CZLG600DLL_TESTDlg::OnBUTTON1Open() 
{
	// TODO: Add your control notification handler code here
	bool status;
	unsigned char Resualt;
	UINT  BDR[]={CBR_9600, CBR_19200,CBR_28800,CBR_38400, CBR_57600, CBR_115200};
	LocallAddr=AddrBuff[m_CNowAddr.GetCurSel()];          //模块地址
	Format = m_Format.GetCurSel();
	status = ZLG522S_Init(m_uartNum.GetCurSel()+1,BDR[m_uartBdr.GetCurSel()],ZLG522S);
	hCtrl  = ZLG522S_Open(&Resualt,0);
	if(hCtrl != INVALID_HANDLE_VALUE)
	{
		Beep(3000,100);
		AfxMessageBox("模块连接成功!");
		GetDlgItem(IDC_BUTTON2_Close)->EnableWindow(TRUE);
		GetDlgItem(IDC_BUTTON1_Open)->EnableWindow(FALSE);

	}
	else{
		if(Resualt == 1) AfxMessageBox("串口打开失败!");
		if(Resualt == 2) AfxMessageBox("模块通信失败!");
        ZLG522S_Exit(hCtrl);
	}
}


void CZLG600DLL_TESTDlg::OnBUTTON2Close() 
{
	// TODO: Add your control notification handler code here
	ZLG522S_Exit(hCtrl);
	Beep(3000,100);
	GetDlgItem(IDC_BUTTON1_Open)->EnableWindow(TRUE);
	GetDlgItem(IDC_BUTTON2_Close)->EnableWindow(FALSE);
}



void CZLG600DLL_TESTDlg::OnBUTTONSetBDR() 
{
	// TODO: Add your control notification handler code here
	UCHAR   num,statues;
	UCHAR   SFormat,SAddr,CmMode;

	num = m_UARTBDR.GetCurSel();
    
//	m_Addr.GetData(&SAddr,1);
	SAddr = AddrBuff[m_NewADDR.GetCurSel()];
	
	SFormat=m_Format.GetCurSel();
	CmMode = m_cMode.GetCurSel();           //获取当前通信模式
	if(CmMode==1){AfxMessageBox("模式错误");return;}
    statues = PCDSetWordMode(m_cMode.GetCurSel(),SAddr);//设定模块为串口通信，地址为0xB2
	LocallAddr = SAddr;                     //必须放到后面
	  
	  if(statues == 0x00 )
	  {
		 statues= PCDSetFormat(SFormat);
		 if(SFormat)ModulFormat = 1;
		 else ModulFormat = 0;
		 if(statues == 0x00)
		 {
			 statues = PCDSetDAUD(num);
			 if(statues == 0x00)
			 {
				 	AfxMessageBox("模块设置成功!");
			 }else{
			  AfxMessageBox("模块设置失败!");
			 }
		 }
	  }
	
}

void CZLG600DLL_TESTDlg::OnSelchangeCOMBOFormat() 
{
	// TODO: Add your control notification handler code here

}

void CZLG600DLL_TESTDlg::OnChangeEDITAddr() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
    
	
}

void CZLG600DLL_TESTDlg::OnSelchangeCOMBONowFormat() 
{
	// TODO: Add your control notification handler code here
	ModulFormat = m_NowFormat.GetCurSel();	
	if(ModulFormat==0){
		GetDlgItem(IDC_COMBO_NowAddr)->EnableWindow(FALSE);//旧帧格式时，关闭地址选项
	}else{

		GetDlgItem(IDC_COMBO_NowAddr)->EnableWindow(TRUE);//旧帧格式时，关闭地址选项
	}
}

void CZLG600DLL_TESTDlg::OnChangeEDITNowAddr() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	m_NowAddr.GetData(&LocallAddr,1);
}

void CZLG600DLL_TESTDlg::OnSelendcancelCOMBONowFormat() 
{
	// TODO: Add your control notification handler code here

			ModulFormat = m_NowFormat.GetCurSel();	
}

void CZLG600DLL_TESTDlg::OnEditchangeCOMBONowAddr() 
{
	// TODO: Add your control notification handler code here
	LocallAddr=AddrBuff[m_CNowAddr.GetCurSel()];          //模块地址
}
