// BCC_CalculateDlg.cpp : implementation file
//

#include "stdafx.h"
#include "BCC_Calculate.h"
#include "BCC_CalculateDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static unsigned char BCC_Direct(unsigned char *p,unsigned char length,unsigned char mode);
static unsigned short BCC_ADD(unsigned char *p,unsigned char length);
/////////////////////////////////////////////////////////////////////////////
// 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()

/////////////////////////////////////////////////////////////////////////////
// CBCC_CalculateDlg dialog

CBCC_CalculateDlg::CBCC_CalculateDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CBCC_CalculateDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CBCC_CalculateDlg)
	m_sur = _T("");
	m_end = _T("");
	m_qufan = FALSE;
	m_HexBCC = FALSE;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CBCC_CalculateDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CBCC_CalculateDlg)
	DDX_Text(pDX, IDC_EDIT_surse, m_sur);
	DDX_Text(pDX, IDC_EDIT_END, m_end);
	DDX_Check(pDX, IDC_CHECK1, m_qufan);
	DDX_Check(pDX, IDC_CHECK_Hex, m_HexBCC);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CBCC_CalculateDlg, CDialog)
	//{{AFX_MSG_MAP(CBCC_CalculateDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	ON_BN_CLICKED(IDC_BUTTON2, OnButton2)
	ON_BN_CLICKED(IDC_BUTTON3, OnButton3)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CBCC_CalculateDlg message handlers

BOOL CBCC_CalculateDlg::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_qufan = true;    //默认使能取反
	UpdateData(FALSE);
	
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

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

void CBCC_CalculateDlg::OnButton1() 
{
	// TODO: Add your control notification handler code here
	unsigned char Hexdata[60];
	CString copy;
	int lenth = 0;
	int i = 0;
	UpdateData(true);//把外部的输入读进来
	m_end ="";
	//数据进行十六进制转化，
	//m_input +="\r\n";//加上回车符
	lenth = Str2Hex(m_sur,Hexdata);  //返回16进制数据的字节数
	Hexdata[Hexdata[0]-2] = BCC(Hexdata); //计算BCC值
	Hexdata[Hexdata[0]-1] = 0x03;        //结束符

	for(i = 0; i < Hexdata[0]; i++){

	copy.Format("%02X",Hexdata[i]);
	m_end += copy;
	m_end +=' ';
	}
	//m_end += "03";

	UpdateData(false);//内部输出到外部
	
}

/************************************************************************
****将一个十六进制的字符串（str），转化为一个字符数组（data）
****改函数要调用下面HexChar
****
***************************************************************************/
int CBCC_CalculateDlg::Str2Hex(CString str, unsigned char* data)
{
	int t, t1;
	int rlen = 0, len = str.GetLength();
	for (int i = 0; i < len;)
	{
		char l, h = str[i];
		if (h == ' ')  //如果有空格
		{
			i++;
			continue;
		}
		i++;
		if(i >= len) break;
		l = str[i];
		t = HexChar(h);
		t1 = HexChar(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 CBCC_CalculateDlg::HexChar(char c)
{
	if((c>='0')&&(c<='9'))
		return c-0x30;
	else if((c>='A')&&(c<='F'))
		return c-'A'+10;
	else if((c>='a')&&(c<='f'))
		return c-'a'+10;
	else
		return 0x10;
}

unsigned char CBCC_CalculateDlg::BCC(unsigned char *p)
{
	unsigned char BCC = 0; 
    unsigned char i = 0;	
	for (i = 0; i < (p[0] - 2); i++) { 
	BCC ^= p[i]; 
	}
	return (~BCC) ;
}

unsigned char BCC_Direct(unsigned char *p,unsigned char length,unsigned char mode)
{
	unsigned char BCC = 0; 
	unsigned char HexBCC=0;
    unsigned char i = 0;	
	if(mode == 0)
	{
		for (i = 0; i < length; i++) 
		{ 
			BCC ^= p[i]; 
		}
	}else if(mode ==1 )
		{
			for (i = 0; i < length; i++) 
			{ 
				HexBCC += p[i]; 
			}
			BCC = HexBCC;
		}

	return (~BCC) ;
}

unsigned short BCC_ADD(unsigned char *p,unsigned char length)
{
	unsigned short BCC = 0x000; 
    unsigned char i = 0;	
	for (i = 0; i < length; i++) { 
		BCC += p[i]; 
	}
	return (~BCC) ;
}

void CBCC_CalculateDlg::OnButton2() 
{
	// TODO: Add your control notification handler code here
	// TODO: Add your control notification handler code here
	unsigned char Hexdata[60];
	CString copy;
	int lenth = 0;
	int i = 0;
	unsigned char Data=0;
	UpdateData(true);//把外部的输入读进来
	m_end ="";
	//数据进行十六进制转化，
	//m_input +="\r\n";//加上回车符
	lenth = Str2Hex(m_sur,Hexdata);  //返回16进制数据的字节数
	if(m_HexBCC){  
		Data = BCC_Direct(Hexdata,lenth,1);
	}else{
        Data = BCC_Direct(Hexdata,lenth,0);
	}

	if(m_qufan==FALSE){
		Data = ~Data;
	}
	if(m_HexBCC) Data = 0x100-Data;
	m_end.Format(_T("%02X"),Data);

	UpdateData(false);//内部输出到外部
}

void CBCC_CalculateDlg::OnButton3() 
{
	// TODO: Add your control notification handler code here
	unsigned char Hexdata[60];
	CString copy;
	int lenth = 0;
	int i = 0;
	unsigned short Data=0;
	UpdateData(true);//把外部的输入读进来
	m_end ="";
	//数据进行十六进制转化，
	//m_input +="\r\n";//加上回车符
	lenth = Str2Hex(m_sur,Hexdata);  //返回16进制数据的字节数
	
	Data = BCC_ADD(Hexdata,lenth);
	m_end.Format(_T("%02X"),Data);
	
	UpdateData(false);//内部输出到外部
	
}
