
// C_InitTagDlg.cpp : implementation file

#include "pch.h"
#include "framework.h"
#include "C_InitTag.h"
#include "C_InitTagDlg.h"
#include "afxdialogex.h"
#include "windowsx.h"
#include <string>

#ifdef _DEBUG
	#define new DEBUG_NEW
#endif


// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
	public:
		CAboutDlg();

	// Dialog Data
	#ifdef AFX_DESIGN_TIME
		enum { IDD = IDD_ABOUTBOX };
	#endif

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

	// Implementation
	protected:
		DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) {}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CCInitTagDlg dialog
CCInitTagDlg::CCInitTagDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_C_INITTAG_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CCInitTagDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_editPort, port);
	DDX_Control(pDX, IDC_editAntcnt, antCnt);
	DDX_Control(pDX, IDC_editAnt, opAnt);
	DDX_Control(pDX, IDC_editAccPwd, accPwd);
	DDX_Control(pDX, IDC_editKillPwd, killPwd);
	DDX_Control(pDX, IDC_editEpc, epc);
	DDX_Control(pDX, IDC_editBank, bank);
	DDX_Control(pDX, IDC_editAddress, addr);
	DDX_Control(pDX, IDC_editData, data);
}

BEGIN_MESSAGE_MAP(CCInitTagDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_openReader, &CCInitTagDlg::OnBnClickedopenReader)
	ON_BN_CLICKED(IDC_writeepc, &CCInitTagDlg::OnBnClickedwriteepc)
	ON_BN_CLICKED(IDC_writebank, &CCInitTagDlg::OnBnClickedwritebank)
	ON_BN_CLICKED(IDC_readbank, &CCInitTagDlg::OnBnClickedreadbank)
	ON_BN_CLICKED(IDC_locktag, &CCInitTagDlg::OnBnClickedlocktag)
	ON_BN_CLICKED(IDC_killtag, &CCInitTagDlg::OnBnClickedkilltag)
	ON_BN_CLICKED(IDC_inittag, &CCInitTagDlg::OnBnClickedinittag)
END_MESSAGE_MAP()


bool CCInitTagDlg::PreTagOp()
{
	READER_ERR err = MT_OK_ERR;
	CString tipstr;
	CString tmpnum;

	CString ant_s;
	opAnt.GetWindowText(ant_s);
	int ant = _ttoi(ant_s);
	int ants[] = { ant };

	int tagcnt;
	TAGINFO tag;
	TagFilter_ST filter;

	// Inventory 300ms, detect the number of tags present in the antenna field
	err = TagInventory_Raw(m_hreader, ants, 1, 300, &tagcnt);
	if (err != MT_OK_ERR)
	{
		tipstr = "Inventory failed, error code:";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
		return false;
	}
	if (tagcnt != 1)
	{
		MessageBox(_T("Make sure that there is only one tag in the antenna field."));
		return false;
	}

	// Obtain the EPC code of the unique tag that exists in the current antenna field
	err = GetNextTag(m_hreader, &tag);
	if (err != MT_OK_ERR)
	{
		tipstr = "Failed to get tag, error code:";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
		return false;
	}

	// Set the EPC code of the tag as the filter condition for future tag operations
	filter.bank = 1;
	filter.fdata = tag.EpcId;
	filter.flen = tag.Epclen * 8;
	filter.startaddr = 32;
	filter.isInvert = 0;
	ParamSet(m_hreader, MTR_PARAM_TAG_FILTER, &filter);

	return true;
}


READER_ERR CCInitTagDlg::OpenReader()
{
	READER_ERR err = MT_OK_ERR;
	if (m_hreader != -1)
	{
		CloseReader(m_hreader);
		m_hreader = -1;
	}

	// Example of initialization of the reader
    // When connecting using the device's network port, the second parameter
	// of the InitReader_Notype function can also be an IP address.
	CString port_s;
	port.GetWindowText(port_s);
	CT2A port_c(port_s);

	CString antCnt_s;
	antCnt.GetLBText(antCnt.GetCurSel(), antCnt_s);

	err = InitReader_Notype(&m_hreader, port_c, _ttoi(antCnt_s)); 
	if (err != MT_OK_ERR) 
		return err;

	// The following parameters must be set
	AntPowerConf pwrs;
	pwrs.antcnt = _ttoi(antCnt_s);

	// The transmitter power of the reader is set to 24 dBm, which is not suitable for initialization tag applications.
	// It is too large, but in practice it should be adjusted according to the application environment and the performance of the tag used
	// Generally speaking, the higher the power, the farther the identification distance
	for (int i = 0; i < _ttoi(antCnt_s); ++i)
	{ 
		pwrs.Powers[i].antid = i + 1; 
		pwrs.Powers[i].readPower = 2400; 
		pwrs.Powers[i].writePower = 2400;
	} 
	err = ParamSet(m_hreader, MTR_PARAM_RF_ANTPOWER, &pwrs);
	if (err != MT_OK_ERR)
		return err;

	Region_Conf region = RG_EU3;
	err = ParamSet(m_hreader, MTR_PARAM_FREQUENCY_REGION, &region);
	if (err != MT_OK_ERR)
		return err;
    
	// Set the reader to execute the GEN2 air interface protocol
	Inv_Potls_ST potls;
	potls.potlcnt = 1; 
	potls.potls[0].potl = SL_TAG_PROTOCOL_GEN2; 
	potls.potls[0].weight = 30; 
	ParamSet(m_hreader, MTR_PARAM_TAG_INVPOTL, &potls);
	
	return MT_OK_ERR;
}


// CCInitTagDlg message handlers
BOOL CCInitTagDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 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 != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		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

	antCnt.AddString(_T("1"));
	antCnt.AddString(_T("2"));
	antCnt.AddString(_T("4"));
	antCnt.AddString(_T("8"));
	antCnt.AddString(_T("16"));
	antCnt.SetCurSel(3);

	port.SetWindowTextW(_T("192.168.10.99"));
	opAnt.SetWindowTextW(_T("1"));
	accPwd.SetWindowTextW(_T("00000000"));
	killPwd.SetWindowTextW(_T("00000000"));
	epc.SetWindowTextW(_T("012345678901234567890129"));
	bank.SetWindowTextW(_T("1"));
	addr.SetWindowTextW(_T("2"));
	
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CCInitTagDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::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 CCInitTagDlg::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 CCInitTagDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CCInitTagDlg::OnClose()
{
	if (m_hreader != -1)
		CloseReader(m_hreader);
	
	CDialog::OnClose();
}

void CCInitTagDlg::OnBnClickedopenReader()
{
	READER_ERR err = OpenReader();
	if (err != MT_OK_ERR)
	{
		CString tmp;
		CString errstring = _T("Failed to initialize the reader:");
		tmp.Format(_T("%d"), err);
		errstring += tmp;
		MessageBox(errstring);
		CDialog::OnOK();
	}
}

/*
 * Write the EPC code to the tag
 * However, please note that both the WriteTagEpcEx and WriteTagData methods can
 * modify the data of the EPC area of the tag, and there are several bits in the
 * PC segment of the EPC area that are used to indicate the length of the EPC code
 * returned to the reader when the inventory operation (corresponding to the Read method)
 * is performed, that is to say, the length of the returned EPC code can be less
 * than the capacity of the actual EPC area, and the WriteTagEpcEx method will write
 * data to the EPC area starting from block address 2. At the same time, the bit 
 * of the EPC code length indicating the inventory operation in the PC segment is
 * indicating the length of the written data, that is, the data written by the WriteTagEpcEx
 * method will be exactly the same as the data read by the Read method.
 * The WriteTagData method can modify any writable storage area in the EPC area.
 * */
void CCInitTagDlg::OnBnClickedwriteepc()
{
	READER_ERR err = MT_OK_ERR;
	CString tipstr;
	CString tmpnum;

	if (!PreTagOp())
		return;

	// Initialize the EPC code to be written
	CString epc_s;
	epc.GetWindowText(epc_s);
	CT2A epc_c(epc_s);
	unsigned char wepc[12];
	Str2Hex(epc_c, epc_s.GetLength(), wepc);

	// When the tag leaves the factory, the access password is all 0. 
	// If the tag has already been locked, set the access password according to the actual situation.
	CString accpwd_s;
	accPwd.GetWindowText(accpwd_s);
	CT2A accpwd_c(accpwd_s);
	unsigned char accesspwd[4];
	Str2Hex(accpwd_c, accpwd_s.GetLength(), accesspwd);

	// Operating antenna
	CString opAnt_s;
	opAnt.GetWindowText(opAnt_s);

	// The timeout period is set to 1000 ms for EPC code writing operations, meaning that 
	// the operation will block for at most 1000 ms.
	// If the operation is completed within the timeout period or if there is an error, 
	// it will return early
	err = WriteTagEpcEx(m_hreader, _ttoi(opAnt_s), wepc, 12, accesspwd, 1000);
	if (err != MT_OK_ERR)
	{
		int dtcode;
		char* dterr;
		GetLastDetailError(m_hreader, &dtcode, &dterr);
		tipstr = "Operation failed, error code: ";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
	}
	else
	{
		// Because the current tag is set as the filter condition before the operation, 
		// the filter condition should be removed after the operation is successful, 
		// otherwise it will affect the number of tags detected in the antenna field 
		// before the next tag operation.
		ParamSet(m_hreader, MTR_PARAM_TAG_FILTER, NULL);
		MessageBox(_T("Operation successful"));
	}
}

/*
 * Write data to the tag storage area.
 * */
void CCInitTagDlg::OnBnClickedwritebank()
{
	READER_ERR err = MT_OK_ERR;
	CString tipstr;
	CString tmpnum;

	if (!PreTagOp())
		return;

	CString data_s;
	data.GetWindowText(data_s);
	CT2A data_c(data_s);
	unsigned char wdata[4];
	Str2Hex(data_c, data_s.GetLength(), wdata);
	
	// When the tag leaves the factory, the access password is all 0. 
	// If the tag has already been locked, set the access password according to the actual situation.
	CString accpwd_s;
	accPwd.GetWindowText(accpwd_s);
	CT2A accpwd_c(accpwd_s);
	unsigned char accesspwd[4];
	Str2Hex(accpwd_c, accpwd_s.GetLength(), accesspwd);

	CString opAnt_s;
	opAnt.GetWindowText(opAnt_s);
	CString bank_s;
	bank.GetWindowText(bank_s);
	CString addr_s;
	addr.GetWindowText(addr_s);

	// The timeout period is set to 1000 ms for EPC code writing operations, meaning that 
	// the operation will block for at most 1000 ms.
	// If the operation is completed within the timeout period or if there is an error, 
	// it will return early
	err = WriteTagData(m_hreader, _ttoi(opAnt_s), _ttoi(bank_s), _ttoi(addr_s), wdata, 4, accesspwd, 1000);
	if (err != MT_OK_ERR)
	{
		tipstr = "Operation failed, error code: ";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
	}
	else
	{
		// Because the current tag is set as the filter condition before the operation, 
		// the filter condition should be removed after the operation is successful, otherwise 
		// it will affect the number of tags detected in the antenna field before the next tag 
		// operation.
		ParamSet(m_hreader, MTR_PARAM_TAG_FILTER, NULL);
		MessageBox(_T("Operation successful"));
	}
}

/*
 * Read the data in the tag storage area.
 * */
void CCInitTagDlg::OnBnClickedreadbank()
{
	READER_ERR err = MT_OK_ERR;
	CString tipstr;
	CString tmpnum;
	unsigned char rdata[4];

	if (!PreTagOp())
		return;

	// When the tag leaves the factory, the access password is all 0. 
	// If the tag has already been locked, set the access password according to the actual situation.
	CString accpwd_s;
	accPwd.GetWindowText(accpwd_s);
	CT2A accpwd_c(accpwd_s);
	unsigned char accesspwd[4];
	Str2Hex(accpwd_c, accpwd_s.GetLength(), accesspwd);

	CString opAnt_s;
	opAnt.GetWindowText(opAnt_s);
	CString bank_s;
	bank.GetWindowText(bank_s);
	CString addr_s;
	addr.GetWindowText(addr_s);

	// The timeout period is set to 1000 ms for EPC code writing operations, meaning that 
	// the operation will block for at most 1000 ms.
	// If the operation is completed within the timeout period or if there is an error, 
	// it will return early
	err = GetTagData(m_hreader, _ttoi(opAnt_s), _ttoi(bank_s), _ttoi(addr_s), 2, rdata, accesspwd, 1000);
	if (err != MT_OK_ERR)
	{
		tipstr = "Operation failed, error code: ";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
	}
	else
	{
		// Because the current tag is set as the filter condition before the operation, 
		// the filter condition should be removed after the operation is successful, otherwise 
		// it will affect the number of tags detected in the antenna field before the next tag 
		// operation.
		ParamSet(m_hreader, MTR_PARAM_TAG_FILTER, NULL);
		MessageBox(_T("Operation successful"));
		CString msg;
		msg.Format(_T("%02x%02x%02x%02x"), rdata[0], rdata[1], rdata[2], rdata[3]);
		MessageBox(msg);
	}
}

/*
 * Lock the tag storage areas.
 * In this example, the EPC bank of the tag is temporarily locked.
 * It should be noted that before locking the tag storage bank, it is generally necessary to
 * initialize the tag access password to non-zero, otherwise the operation will fail.
 * Initializing the tag access password can be operated through the WriteTagData method.
 * */
void CCInitTagDlg::OnBnClickedlocktag()
{
	READER_ERR err = MT_OK_ERR;
	CString tipstr;
	CString tmpnum;

	if (!PreTagOp())
		return;

	CString accpwd_s;
	accPwd.GetWindowText(accpwd_s);
	CT2A accpwd_c(accpwd_s);
	unsigned char accesspwd[4];
	Str2Hex(accpwd_c, accpwd_s.GetLength(), accesspwd);

	CString opAnt_s;
	opAnt.GetWindowText(opAnt_s);

	// The timeout period is set to 1000 ms for EPC code writing operations, meaning that 
	// the operation will block for at most 1000 ms.
	// If the operation is completed within the timeout period or if there is an error, 
	// it will return early
	err = LockTag(m_hreader, _ttoi(opAnt_s), LOCK_OBJECT_BANK1, BANK1_LOCK, accesspwd, 1000);
	if (err != MT_OK_ERR)
	{
		tipstr = "Operation failed, error code: ";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
	}
	else
	{
		// Because the current tag is set as the filter condition before the operation, 
		// the filter condition should be removed after the operation is successful, 
		// otherwise it will affect the number of tags detected in the antenna field 
		// before the next tag operation.
		ParamSet(m_hreader, MTR_PARAM_TAG_FILTER, NULL);
		MessageBox(_T("Operation successful"));
	}
}

/*
 * Kill the tag. Once the tag is killed, it can no longer be used.
 * It should be noted that the tag can only be killed if it is initialized with a
 * non-zero kill password.
 * */
void CCInitTagDlg::OnBnClickedkilltag()
{
	READER_ERR err = MT_OK_ERR;
	CString tipstr;
	CString tmpnum;

	if (!PreTagOp())
		return;

	CString killpwd_s;
	killPwd.GetWindowText(killpwd_s);
	CT2A killpwd_c(killpwd_s);
	unsigned char killpwd[4];
	Str2Hex(killpwd_c, killpwd_s.GetLength(), killpwd);

	CString opAnt_s;
	opAnt.GetWindowText(opAnt_s);

	// The timeout period is set to 1000 ms for EPC code writing operations, meaning that 
	// the operation will block for at most 1000 ms.
	// If the operation is completed within the timeout period or if there is an error, 
	// it will return early
	err = KillTag(m_hreader,_ttoi(opAnt_s), killpwd, 1000);
	if (err != MT_OK_ERR)
	{
		tipstr = "Operation failed, error code: ";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
	}
	else
	{
		// Because the current tag is set as the filter condition before the operation, 
		// the filter condition should be removed after the operation is successful, 
		// otherwise it will affect the number of tags detected in the antenna field 
		// before the next tag operation.
		ParamSet(m_hreader, MTR_PARAM_TAG_FILTER, NULL);
		MessageBox(_T("Operation successful"));
	}
}

/*
 * Initialize the tag's access password, kill password, and EPC code, and lock
 * the tag's access password, kill password, and EPC area.
 * Note: In the actual application scenario, it is often necessary to lock these storage
 * areas after starting the EPC area or USER area of the tag to prevent unauthorized rewriting.
 * If it is such an application, the access password of the tag must be initialized
 * to be non-zero to lock the other storage area of the tag. If it is considered
 * that the tag may need to be killed in the future, the tag's kill password must
 * also be initialized. Access password and kill password also need to be locked,
 * and these passwords cannot be read and rewritten without authorization.
 * */
void CCInitTagDlg::OnBnClickedinittag()
{
	READER_ERR err = MT_OK_ERR;
	CString tipstr;
	CString tmpnum;
	if (!PreTagOp())
		return;

	CString killpwd_s;
	killPwd.GetWindowText(killpwd_s);
	CT2A killpwd_c(killpwd_s);
	unsigned char killpwd[4];
	Str2Hex(killpwd_c, killpwd_s.GetLength(), killpwd);

	CString accpwd_s;
	accPwd.GetWindowText(accpwd_s);
	CT2A accpwd_c(accpwd_s);
	unsigned char accesspwd[4];
	Str2Hex(accpwd_c, accpwd_s.GetLength(), accesspwd);

	CString epc_s;
	epc.GetWindowText(epc_s);
	CT2A epc_c(epc_s);
	unsigned char wepc[12];
	Str2Hex(epc_c, epc_s.GetLength(), wepc);

	CString opAnt_s;
	opAnt.GetWindowText(opAnt_s);

	// Setting the accesspwd parameter to NULL is equivalent to passing an access password of all 0s.
	err = WriteTagEpcEx(m_hreader, _ttoi(opAnt_s), wepc, 12, NULL, 1000);
	if (err != MT_OK_ERR)
	{
		tipstr = "Operation failed, error code: ";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
		return;
	}

	err = WriteTagData(m_hreader, _ttoi(opAnt_s), 0, 0, killpwd, 4, NULL, 1000);
	if (err != MT_OK_ERR)
	{
		tipstr = "Operation failed, error code: ";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
		return;
	}
	err = WriteTagData(m_hreader, _ttoi(opAnt_s), 0, 2, accesspwd, 4, NULL, 1000);
	if (err != MT_OK_ERR)
	{
		tipstr = "Operation failed, error code: ";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
		return;
	}

	//Lock kill password, access password and EPC area
	err = LockTag(m_hreader, _ttoi(opAnt_s), LOCK_OBJECT_KILL_PASSWORD | LOCK_OBJECT_ACCESS_PASSWD |
		LOCK_OBJECT_BANK1, KILL_PASSWORD_LOCK | ACCESS_PASSWD_LOCK |
		BANK1_LOCK, accesspwd, 1000);
	if (err != MT_OK_ERR)
	{
		tipstr = "Operation failed, error code: ";
		tmpnum.Format(_T("%d"), err);
		tipstr += tmpnum;
		MessageBox(tipstr);
	}
	else
	{
		// Because the current tag is set as the filter condition before the operation, 
		// the filter condition should be removed after the operation is successful, 
		// otherwise it will affect the number of tags detected in the antenna field 
		// before the next tag operation.
		ParamSet(m_hreader, MTR_PARAM_TAG_FILTER, NULL);
		MessageBox(_T("Operation successful"));
	}
}
