using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Resources;
using System.Reflection;
using System.Net;
using System.Threading;
using System.Diagnostics;
using UHF;
using System.IO;
using System.Net.Sockets;

using System.Runtime.InteropServices;
//using System.Net;
using System.Net.NetworkInformation;
using ConfigIni;
using System.Globalization;

namespace UHFReaderDS7Demo
{
    public partial class Form1 : Form
    {
        [DllImport("User32.dll", EntryPoint = "PostMessage")]
        private static extern int PostMessage(
        IntPtr hWnd, // handle to destination window 
        uint Msg, // message 
        uint wParam, // first message parameter 
        uint lParam // second message parameter 
        );

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, string lParam);

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        public static string lang = null;
        public const string LangZh = "zh-CN";

        public static string path = Application.StartupPath;
        public static string iniPath = path + @"\Config.ini";

        public const int USER = 0x0400;
        public const int WM_SENDTAG = USER + 101;
        public const int WM_SENDTAGSTAT = USER + 102;
        public const int WM_SENDSTATU = USER + 103;
        public const int WM_SENDBUFF = USER + 104;
        public const int WM_MIXTAG = USER + 105;
        public const int WM_SHOWNUM = USER + 106;
        public const int WM_FASTID = USER + 107;
        public const int WM_JB_MIX = USER + 108;
        public const int WM_JB_TAG = USER + 109;
        public const int WM_GB_MIX = USER + 110;
        public const int WM_GB_TAG = USER + 111;
        public const int WM_LED_TAG = USER + 112;
        public const int WM_TEMP_TAG = USER + 113;
        public const int WM_TRUTH_TAG = USER + 114;
        public static byte fComAdr = 0xff; //当前操作的ComAdr
        private int ferrorcode;
        private byte fBaud;
        private double fdminfre;
        private double fdmaxfre;
        private int fCmdRet = 30; //所有执行指令的返回值
        private bool fisinventoryscan_6B;
        private byte[] fOperEPC = new byte[100];
        private byte[] fPassWord = new byte[4];
        private byte[] fOperID_6B = new byte[10];
        ArrayList list = new ArrayList();
        private List<string> epclist = new List<string>();
        private List<string> tidlist = new List<string>();
        private int CardNum1 = 0;
        private string fInventory_EPC_List; //存贮询查列表（如果读取的数据没有变化，则不进行刷新）
        public static int frmcomportindex;
        //private bool SeriaATflag = false;
        private byte Target = 0;
        private byte InAnt = 0;
        private byte Scantime = 0;
        private byte FastFlag = 0;
        private byte Qvalue = 0;
        private byte Session = 0;

        private int total_tagnum = 0;//标签数量
        private int CardNum = 0;
        private int NewCardNum = 0;
        private int total_time = 0;//总时间
        private int targettimes = 0;
        private byte TIDFlag = 0;
        private byte tidLen = 0;
        private byte tidAddr = 0;
        public static byte antinfo = 0;
        private int AA_times = 0;
        private int CommunicationTime = 0;
        public DeviceClass SelectedDevice;
        private static List<DeviceClass> DevList;
        private static SearchCallBack searchCallBack = new SearchCallBack(searchCB);
        private string ReadTypes = "";

        private static object LockFlag = new object();


        /// <summary>
        /// Device Search的回调函数;
        /// </summary>
        private static void searchCB(IntPtr dev, IntPtr data)
        {
            uint ipAddr = 0;
            StringBuilder devname = new StringBuilder(100);
            StringBuilder macAdd = new StringBuilder(100);
            //获取搜索到的设备信息；
            DevControl.tagErrorCode eCode = DevControl.DM_GetDeviceInfo(dev, ref ipAddr, macAdd, devname);
            if (eCode == DevControl.tagErrorCode.DM_ERR_OK)
            {
                //将搜索到的设备加入设备列表；
                DeviceClass device = new DeviceClass(dev, ipAddr, macAdd.ToString(), devname.ToString());
                DevList.Add(device);
            }
            else
            {
                //异常处理；
                string errMsg = ErrorHandling.GetErrorMsg(eCode);
                Log.WriteError(errMsg);
            }

        }
        private static IPAddress getIPAddress(uint interIP)
        {
            return new IPAddress((uint)IPAddress.HostToNetworkOrder((int)interIP));
        }
        RFIDCallBack elegateRFIDCallBack;

        RfidTagCallBack myCallBack;
        public Form1()
        {
            InitializeComponent();
            //初始化设备列表；
            DevList = new List<DeviceClass>();

            //初始化设备控制模块；
            DevControl.tagErrorCode eCode = DevControl.DM_Init(searchCallBack, IntPtr.Zero);
            if (eCode != DevControl.tagErrorCode.DM_ERR_OK)
            {
                //如果初始化失败则关闭程序，并进行异常处理；
                string errMsg = ErrorHandling.HandleError(eCode);
                throw new Exception(errMsg);
            }
            elegateRFIDCallBack = new RFIDCallBack(GetUid);
            myCallBack = new RfidTagCallBack(GetEPC);
        }
        volatile List<RFIDTag> curList = new List<RFIDTag>();

        string epcandtid = "";//标记整合数据
        int lastnum = 0;
        public void GetUid(IntPtr p, Int32 nEvt)
        {

            RFIDTag ce = (RFIDTag)Marshal.PtrToStructure(p, typeof(RFIDTag));
            lock (LockFlag)
            {
                curList.Add(ce);
                total_tagnum++;
                CardNum++;
            }
        }


        public void GetEPC(RFIDTag mtag)
        {
            lock (LockFlag)
            {
                curList.Add(mtag);
                total_tagnum++;
            }
        }

        private void SendTagMessage(IntPtr ptrWnd, RFIDTag ce)
        {
            if (mythread != null)
            {
                if (rb_mix.Checked)
                {
                    int gnum = ce.PacketParam;
                    if (gnum < 0x80)//EPC号
                    {
                        lastnum = gnum;
                        epcandtid = ce.UID;
                    }
                    else//附带数据
                    {
                        if (((lastnum & 0x7F) == ((gnum & 0x7F) - 1)) || ((lastnum & 0x7F) == 127 && ((gnum & 0x7F) == 0)))//相邻的滚码
                        {
                            epcandtid = epcandtid + "-" + ce.UID;
                            if (ptrWnd != IntPtr.Zero)         // 检查当前统计窗口是否打开
                            {
                                int Antnum = ce.ANT;
                                string str_ant = GetAntennaNumber(Antnum).ToString();
                                string para = str_ant + "," + epcandtid + "," + ce.RSSI.ToString() + "," + ce.phase_begin + "," + ce.phase_end + "," + ce.Freqkhz;
                                SendMessage(ptrWnd, WM_MIXTAG, IntPtr.Zero, para);
                            }
                        }
                        else
                        {
                            epcandtid = "";
                        }
                    }
                }
                else if (rb_fastid.Checked)
                {
                    int Antnum = ce.ANT;
                    string str_ant = GetAntennaNumber(Antnum).ToString();
                    string epclen = ce.LEN.ToString();
                    string para = str_ant + "," + epclen + "," + ce.UID + "," + ce.RSSI.ToString() + "," + ce.phase_begin + "," + ce.phase_end + "," + ce.Freqkhz;
                    SendMessage(ptrWnd, WM_FASTID, IntPtr.Zero, para);
                }
                else
                {
                    int Antnum = ce.ANT;
                    string str_ant = GetAntennaNumber(Antnum).ToString();// Convert.ToString(Antnum, 2).PadLeft(4, '0');
                    string epclen = ce.LEN.ToString();// Convert.ToString(ce.LEN, 16);
                    string para = str_ant + "," + epclen + "," + ce.UID + "," + ce.RSSI.ToString() + "," + ce.phase_begin + "," + ce.phase_end + "," + ce.Freqkhz;
                    SendMessage(ptrWnd, WM_SENDTAG, IntPtr.Zero, para);
                }
            }
        }
        private int GetAntennaNumber(int ant)
        {
            int Antenna = 1;
            if (AntennaNum > 8)
            {
                return ant + 1;
            }
            else
            {
                switch (ant)
                {
                    case 0x01:
                        Antenna = 1;
                        break;
                    case 0x02:
                        Antenna = 2;
                        break;
                    case 0x04:
                        Antenna = 3;
                        break;
                    case 0x08:
                        Antenna = 4;
                        break;
                    case 0x10:
                        Antenna = 5;
                        break;
                    case 0x20:
                        Antenna = 6;
                        break;
                    case 0x40:
                        Antenna = 7;
                        break;
                    case 0x80:
                        Antenna = 8;
                        break;
                }
            }
            return Antenna;
        }
        DataTable dt = null;
        int scanType = 0;
        protected override void DefWndProc(ref Message m)
        {
            if (m.Msg == WM_SENDTAG)
            {

                string tagInfo = Marshal.PtrToStringAnsi(m.LParam);
                string[] btArr = tagInfo.Split(',');
                string sEPC;
                string str_ant = btArr[0];
                sEPC = btArr[2];
                string str_epclen = btArr[1]; ;
                byte epclen = Convert.ToByte(str_epclen, 10);
                string RSSI = btArr[3];
                int phase_begin = Convert.ToInt32(btArr[4], 10);
                int phase_end = Convert.ToInt32(btArr[5], 10);
                int freqkhz = Convert.ToInt32(btArr[6], 10);
                if (scanType == 0)
                    updateEPC(sEPC, RSSI, str_ant, phase_begin, phase_end, freqkhz);
                else if (scanType == 1)
                    updateTID(sEPC, RSSI, str_ant, phase_begin, phase_end, freqkhz);
                else if (scanType == 2)
                    updateFastID(sEPC, RSSI, str_ant, phase_begin, phase_end, freqkhz);
                bool flagset = false;
                flagset = (dataGridView1.DataSource == null) ? true : false;
                dataGridView1.DataSource = dt;

                if (flagset)
                {
                    dataGridView1.Columns["Column1"].HeaderText = ResourceCulture.GetString("hint_number"); 
                    dataGridView1.Columns["Column1"].Width = 60;
                    dataGridView1.Columns["Column2"].HeaderText = "EPC";
                    dataGridView1.Columns["Column2"].Width = 170;
                    dataGridView1.Columns["Column3"].HeaderText = ResourceCulture.GetString("hint_count"); 
                    dataGridView1.Columns["Column3"].Width = 60;
                    dataGridView1.Columns["Column4"].HeaderText = "RSSI";
                    dataGridView1.Columns["Column4"].Width = 60;
                    dataGridView1.Columns["Column5"].HeaderText = ResourceCulture.GetString("hint_begin_phase");
                    dataGridView1.Columns["Column5"].Width = 80;
                    dataGridView1.Columns["Column6"].HeaderText = ResourceCulture.GetString("hint_end_phase");
                    dataGridView1.Columns["Column6"].Width = 80;
                    dataGridView1.Columns["Column7"].HeaderText = ResourceCulture.GetString("hint_antenna");
                    dataGridView1.Columns["Column7"].Width = 80;
                    dataGridView1.Columns["Column8"].HeaderText = ResourceCulture.GetString("hint_freq");
                    dataGridView1.Columns["Column8"].Width = 90;
                }
            }
            else if (m.Msg == WM_MIXTAG)
            {
                string tagInfo = Marshal.PtrToStringAnsi(m.LParam);
                string[] btArr = tagInfo.Split(',');
                string sEPC, sData;
                string str_ant = btArr[0];
                sEPC = btArr[1];
                int n = sEPC.IndexOf("-");
                sData = sEPC.Substring(n + 1);
                sEPC = sEPC.Substring(0, n);
                string RSSI = btArr[2];

                int phase_begin = Convert.ToInt32(btArr[3], 10);
                int phase_end = Convert.ToInt32(btArr[4], 10);
                int freqkhz = Convert.ToInt32(btArr[5], 10);
                DataTable dt = dataGridView1.DataSource as DataTable;

                if (dt == null)
                {
                    dt = new DataTable();
                    dt.Columns.Add("Column1", Type.GetType("System.String"));
                    dt.Columns.Add("Column2", Type.GetType("System.String"));
                    dt.Columns.Add("Column3", Type.GetType("System.String"));
                    dt.Columns.Add("Column4", Type.GetType("System.String"));
                    dt.Columns.Add("Column5", Type.GetType("System.String"));
                    dt.Columns.Add("Column6", Type.GetType("System.String"));
                    dt.Columns.Add("Column7", Type.GetType("System.String"));
                    dt.Columns.Add("Column8", Type.GetType("System.String"));
                    dt.Columns.Add("Column9", Type.GetType("System.String"));
                    DataRow dr = dt.NewRow();
                    dr["Column1"] = (dt.Rows.Count + 1).ToString();
                    dr["Column2"] = sEPC;
                    dr["Column3"] = sData;
                    dr["Column4"] = "1";
                    dr["Column5"] = RSSI;
                    dr["Column6"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                    dr["Column7"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dr["Column8"] = str_ant;
                    dr["Column9"] = freqkhz + "";
                    dt.Rows.Add(dr);
                    epclist.Add(sEPC);
                    lxLedControl1.Text = dt.Rows.Count.ToString();
                    //lxLedControl5.Text = dt.Rows.Count.ToString();
                    comboBox_EPC.Items.Add(sEPC);
                }
                else
                {
                    DataRow[] dr;
                    dr = dt.Select("Column2='" + sEPC + "'");
                    if (dr.Length == 0)     // epc号不存在
                    {
                        DataRow dr2 = dt.NewRow();
                        dr2["Column1"] = (dt.Rows.Count + 1).ToString();
                        dr2["Column2"] = sEPC;
                        dr2["Column3"] = sData;
                        dr2["Column4"] = "1";
                        dr2["Column5"] = RSSI;
                        dr2["Column6"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                        dr2["Column7"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                        dr2["Column8"] = str_ant;
                        dr2["Column9"] = freqkhz + "";
                        dt.Rows.Add(dr2);
                        lxLedControl1.Text = dt.Rows.Count.ToString();
                        lxLedControl5.Text = (System.Environment.TickCount - total_time).ToString();
                        epclist.Add(sEPC);
                        comboBox_EPC.Items.Add(sEPC);
                    }
                    else     // epc号已存在
                    {
                        int cnt = int.Parse(dr[0]["Column4"].ToString());
                        cnt++;
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column4"] = cnt.ToString();
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column5"] = RSSI;
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column6"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column7"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column8"] = str_ant;
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column9"] = freqkhz + "";
                    }
                }
                bool flagset = false;
                flagset = (dataGridView1.DataSource == null) ? true : false;
                dataGridView1.DataSource = dt;

                if (flagset)
                {
                    dataGridView1.Columns["Column1"].HeaderText = ResourceCulture.GetString("hint_number");
                    dataGridView1.Columns["Column1"].Width = 60;

                    dataGridView1.Columns["Column2"].HeaderText = "EPC";
                    dataGridView1.Columns["Column2"].Width = 100;

                    dataGridView1.Columns["Column3"].HeaderText = ResourceCulture.GetString("hint_memory");
                    dataGridView1.Columns["Column3"].Width = 90;

                    dataGridView1.Columns["Column4"].HeaderText = ResourceCulture.GetString("hint_count");
                    dataGridView1.Columns["Column4"].Width = 60;

                    dataGridView1.Columns["Column5"].HeaderText = "RSSI";
                    dataGridView1.Columns["Column5"].Width = 60;

                    dataGridView1.Columns["Column6"].HeaderText = ResourceCulture.GetString("hint_begin_phase");
                    dataGridView1.Columns["Column6"].Width = 80;

                    dataGridView1.Columns["Column7"].HeaderText = ResourceCulture.GetString("hint_end_phase");
                    dataGridView1.Columns["Column7"].Width = 80;


                    dataGridView1.Columns["Column8"].HeaderText = ResourceCulture.GetString("hint_antenna");
                    dataGridView1.Columns["Column8"].Width = 80;
                    dataGridView1.Columns["Column9"].HeaderText = ResourceCulture.GetString("hint_freq");
                    dataGridView1.Columns["Column9"].Width = 90;
                }
            }
            else if (m.Msg == WM_FASTID)
            {//string para = str_ant + "," + epclen+"," + ce.UID + "," + ce.RSSI.ToString();
                string tagInfo = Marshal.PtrToStringAnsi(m.LParam);
                string[] btArr = tagInfo.Split(',');
                string sEPC = btArr[2];
                string sTID = "";
                string str_ant = btArr[0];
                string str_epclen = btArr[1];
                byte nlen = Convert.ToByte(str_epclen, 10);
                if ((nlen & 0x80) == 0)
                {
                    if (epclist.IndexOf(sEPC) == -1)
                    {
                        epclist.Add(sEPC);
                    }
                    lxLedControl1.Text = epclist.Count.ToString();
                }
                else
                {
                    int epclen = (nlen & 0x3F) - 12;
                    sTID = sEPC.Substring(epclen * 2, 24);
                    sEPC = sEPC.Substring(0, epclen * 2);
                    if (epclist.IndexOf(sEPC) == -1)
                    {
                        epclist.Add(sEPC);
                    }
                    if (tidlist.IndexOf(sTID) == -1)
                    {
                        tidlist.Add(sTID);
                    }
                    lxLedControl1.Text = epclist.Count.ToString();
                    lxLedControl6.Text = tidlist.Count.ToString();

                }
                string RSSI = btArr[3];

                int phase_begin = Convert.ToInt32(btArr[4], 10);
                int phase_end = Convert.ToInt32(btArr[5], 10);
                int freqkhz = Convert.ToInt32(btArr[6], 10);
                DataTable dt = dataGridView1.DataSource as DataTable;

                if (dt == null)
                {
                    dt = new DataTable();
                    dt.Columns.Add("Column1", Type.GetType("System.String"));
                    dt.Columns.Add("Column2", Type.GetType("System.String"));
                    dt.Columns.Add("Column3", Type.GetType("System.String"));
                    dt.Columns.Add("Column4", Type.GetType("System.String"));
                    dt.Columns.Add("Column5", Type.GetType("System.String"));
                    dt.Columns.Add("Column6", Type.GetType("System.String"));
                    dt.Columns.Add("Column7", Type.GetType("System.String"));
                    dt.Columns.Add("Column8", Type.GetType("System.String"));
                    dt.Columns.Add("Column9", Type.GetType("System.String"));
                    DataRow dr = dt.NewRow();
                    dr["Column1"] = (dt.Rows.Count + 1).ToString();
                    dr["Column2"] = sEPC;
                    dr["Column3"] = sTID;
                    dr["Column4"] = "1";
                    dr["Column5"] = RSSI;

                    dr["Column6"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                    dr["Column7"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dr["Column8"] = str_ant;
                    dr["Column9"] = freqkhz + "";
                    dt.Rows.Add(dr);
                    //lxLedControl1.Text = dt.Rows.Count.ToString();
                    lxLedControl5.Text = dt.Rows.Count.ToString();
                    comboBox_EPC.Items.Add(sEPC);
                }
                else
                {
                    DataRow[] dr;
                    dr = dt.Select("Column2='" + sEPC + "' and Column3='" + sTID + "'");
                    if (dr.Length == 0)     // epc号不存在
                    {
                        DataRow dr2 = dt.NewRow();
                        dr2["Column1"] = (dt.Rows.Count + 1).ToString();
                        dr2["Column2"] = sEPC;
                        dr2["Column3"] = sTID;
                        dr2["Column4"] = "1";
                        dr2["Column5"] = RSSI;
                        dr2["Column6"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                        dr2["Column7"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                        dr2["Column8"] = str_ant;
                        dr2["Column9"] = freqkhz + "";
                        dt.Rows.Add(dr2);
                        //lxLedControl1.Text = dt.Rows.Count.ToString();
                        lxLedControl5.Text = (System.Environment.TickCount - total_time).ToString();
                        comboBox_EPC.Items.Add(sEPC);
                    }
                    else     // epc号已存在
                    {
                        int cnt = int.Parse(dr[0]["Column4"].ToString());
                        cnt++;
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column4"] = cnt.ToString();
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column5"] = RSSI;
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column6"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column7"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column8"] = str_ant;
                        dt.Rows[dt.Rows.IndexOf(dr[0])]["Column9"] = freqkhz + "";
                    }
                }
                bool flagset = false;
                flagset = (dataGridView1.DataSource == null) ? true : false;
                dataGridView1.DataSource = dt;

                if (flagset)
                {
                    dataGridView1.Columns["Column1"].HeaderText = ResourceCulture.GetString("hint_number");
                    dataGridView1.Columns["Column1"].Width = 60;

                    dataGridView1.Columns["Column2"].HeaderText = "EPC";
                    dataGridView1.Columns["Column2"].Width = 100;

                    dataGridView1.Columns["Column3"].HeaderText = "     TID";
                    dataGridView1.Columns["Column3"].Width = 90;

                    dataGridView1.Columns["Column4"].HeaderText = ResourceCulture.GetString("hint_count");
                    dataGridView1.Columns["Column4"].Width = 60;

                    dataGridView1.Columns["Column5"].HeaderText = "RSSI";
                    dataGridView1.Columns["Column5"].Width = 60;

                    dataGridView1.Columns["Column6"].HeaderText = ResourceCulture.GetString("hint_begin_phase");
                    dataGridView1.Columns["Column6"].Width = 80;

                    dataGridView1.Columns["Column7"].HeaderText = ResourceCulture.GetString("hint_end_phase");
                    dataGridView1.Columns["Column7"].Width = 80;

                    dataGridView1.Columns["Column8"].HeaderText = ResourceCulture.GetString("hint_antenna");
                    dataGridView1.Columns["Column8"].Width = 80;
                    dataGridView1.Columns["Column9"].HeaderText = ResourceCulture.GetString("hint_freq");
                    dataGridView1.Columns["Column9"].Width = 90;
                }
            }
            else if (m.Msg == WM_SENDTAGSTAT)
            {
                string tagInfo = Marshal.PtrToStringAnsi(m.LParam);
                int index = tagInfo.IndexOf(',');
                string tagRate = tagInfo.Substring(0, index);
                index++;
                string str = tagInfo.Substring(index);
                index = str.IndexOf(',');
                string tagNum = str.Substring(0, index);
                index++;
                string cmdTime = str.Substring(index);

                lxLedControl2.Text = tagRate;
                lxLedControl3.Text = cmdTime;
                lxLedControl4.Text = tagNum;
            }
            else if (m.Msg == WM_SENDSTATU)
            {
                string Info = Marshal.PtrToStringAnsi(m.LParam);
                fCmdRet = Convert.ToInt32(Info);
                string strLog = ResourceCulture.GetString("hint_inventory") +":" + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else if (m.Msg == WM_SENDBUFF)
            {
                string tagInfo = Marshal.PtrToStringAnsi(m.LParam);
                int index = tagInfo.IndexOf(',');
                string tagNum = tagInfo.Substring(0, index);
                index++;

                string str = tagInfo.Substring(index);
                index = str.IndexOf(',');
                string cmdTime = str.Substring(0, index);
                index++;

                str = str.Substring(index);
                index = str.IndexOf(',');
                string tagRate = str.Substring(0, index);
                index++;

                str = str.Substring(index);
                string total_tagnum = str;

                WriteLog(lrtxtLog, ResourceCulture.GetString("log_inventory_buffer_succeed"), 1);
            }
            else if (m.Msg == WM_SHOWNUM)
            {
                if (mythread != null)
                    lxLedControl5.Text = (System.Environment.TickCount - total_time).ToString();
            }
            else if (m.Msg == WM_LED_TAG)
            {
                string tagInfo = Marshal.PtrToStringAnsi(m.LParam);
                string[] btArr = tagInfo.Split(',');
                string sEPC;
                string str_ant = btArr[0];
                sEPC = btArr[2];
                string str_epclen = btArr[1]; ;
                byte epclen = Convert.ToByte(str_epclen, 10);
                string RSSI = btArr[3];
                int phase_begin = Convert.ToInt32(btArr[4], 10);
                int phase_end = Convert.ToInt32(btArr[5], 10);
                int freqkhz = Convert.ToInt32(btArr[6], 10);
 
                updateEPC_led(sEPC, RSSI, str_ant, phase_begin, phase_end, freqkhz);
                bool flagset = false;
                flagset = (dataGridView6.DataSource == null) ? true : false;
                dataGridView6.DataSource = dt;

                if (flagset)
                {
                    dataGridView6.Columns["Column1"].HeaderText = ResourceCulture.GetString("hint_check");
                    dataGridView6.Columns["Column1"].Width = 60;
                    dataGridView6.Columns["Column2"].HeaderText = "EPC";
                    dataGridView6.Columns["Column2"].Width = 170;
                    dataGridView6.Columns["Column3"].HeaderText = ResourceCulture.GetString("hint_count");
                    dataGridView6.Columns["Column3"].Width = 60;
                    dataGridView6.Columns["Column4"].HeaderText = "RSSI";
                    dataGridView6.Columns["Column4"].Width = 60;
                    dataGridView6.Columns["Column5"].HeaderText = ResourceCulture.GetString("hint_begin_phase");
                    dataGridView6.Columns["Column5"].Width = 80;
                    dataGridView6.Columns["Column6"].HeaderText = ResourceCulture.GetString("hint_end_phase");
                    dataGridView6.Columns["Column6"].Width = 80;
                    dataGridView6.Columns["Column7"].HeaderText = ResourceCulture.GetString("hint_antenna");
                    dataGridView6.Columns["Column7"].Width = 80;
                    dataGridView6.Columns["Column8"].HeaderText = ResourceCulture.GetString("hint_freq");
                    dataGridView6.Columns["Column8"].Width = 90;
                }
            }
            else if (m.Msg == WM_TEMP_TAG)
            {
                string tagInfo = Marshal.PtrToStringAnsi(m.LParam);
                string[] btArr = tagInfo.Split(',');
                string sEPC;
                string str_ant = btArr[0];
                sEPC = btArr[2];
                string str_epclen = btArr[1]; ;
                byte epclen = Convert.ToByte(str_epclen, 10);
                string RSSI = btArr[3];
                int phase_begin = Convert.ToInt32(btArr[4], 10);
                int phase_end = Convert.ToInt32(btArr[5], 10);
                int freqkhz = Convert.ToInt32(btArr[6], 10);

                updateEPC_TEMP(sEPC, RSSI, str_ant, phase_begin, phase_end, freqkhz);
                bool flagset = false;
                flagset = (dataGridView7.DataSource == null) ? true : false;
                dataGridView7.DataSource = dt;

                if (flagset)
                {
                    dataGridView7.Columns["Column1"].HeaderText = "ID";
                    dataGridView7.Columns["Column1"].Width = 60;
                    dataGridView7.Columns["Column2"].HeaderText = "EPC";
                    dataGridView7.Columns["Column2"].Width = 260;
                    dataGridView7.Columns["Column3"].HeaderText = ResourceCulture.GetString("hint_count");
                    dataGridView7.Columns["Column3"].Width = 60;
                    dataGridView7.Columns["Column4"].HeaderText = "RSSI";
                    dataGridView7.Columns["Column4"].Width = 60;
                    dataGridView7.Columns["Column5"].HeaderText = ResourceCulture.GetString("hint_temperature");
                    dataGridView7.Columns["Column5"].Width = 80;
                    dataGridView7.Columns["Column6"].HeaderText = ResourceCulture.GetString("hint_phase");
                    dataGridView7.Columns["Column6"].Width = 80;
                    dataGridView7.Columns["Column7"].HeaderText = ResourceCulture.GetString("hint_antenna");
                    dataGridView7.Columns["Column7"].Width = 80;
                }
            }
            else if (m.Msg == WM_TRUTH_TAG)
            {
                string tagInfo = Marshal.PtrToStringAnsi(m.LParam);
                string[] btArr = tagInfo.Split(',');
                string sEPC;
                string str_ant = btArr[0];
                sEPC = btArr[2];
                string str_epclen = btArr[1]; ;
                byte epclen = Convert.ToByte(str_epclen, 10);
                string RSSI = btArr[3];
                int phase_begin = Convert.ToInt32(btArr[4], 10);
                int phase_end = Convert.ToInt32(btArr[5], 10);
                int freqkhz = Convert.ToInt32(btArr[6], 10);

                updateEPC_TEMP(sEPC, RSSI, str_ant, phase_begin, phase_end, freqkhz);
                bool flagset = false;
                flagset = (dataGridView8.DataSource == null) ? true : false;
                dataGridView8.DataSource = dt;

                if (flagset)
                {
                    dataGridView8.Columns["Column1"].HeaderText = "ID";
                    dataGridView8.Columns["Column1"].Width = 60;
                    dataGridView8.Columns["Column2"].HeaderText = "EPC";
                    dataGridView8.Columns["Column2"].Width = 260;
                    dataGridView8.Columns["Column3"].HeaderText = ResourceCulture.GetString("hint_count");
                    dataGridView8.Columns["Column3"].Width = 60;
                    dataGridView8.Columns["Column4"].HeaderText = "RSSI";
                    dataGridView8.Columns["Column4"].Width = 60;
                    dataGridView8.Columns["Column5"].HeaderText = ResourceCulture.GetString("hint_status");
                    dataGridView8.Columns["Column5"].Width = 80;
                    dataGridView8.Columns["Column6"].HeaderText = ResourceCulture.GetString("hint_phase");
                    dataGridView8.Columns["Column6"].Width = 80;
                    dataGridView8.Columns["Column7"].HeaderText = ResourceCulture.GetString("hint_antenna");
                    dataGridView8.Columns["Column7"].Width = 80;
                }
            }
            else
                base.DefWndProc(ref m);
        }
        private void updateEPC(string sEPC, string RSSI, string str_ant, int phase_begin, int phase_end, int freqkhz)
        {
            if (epclist.Count == 0)
            {
                epclist.Add(sEPC);
                NewCardNum++;
                dt = dataGridView1.DataSource as DataTable;
                dt = new DataTable();
                dt.Columns.Add("Column1", Type.GetType("System.String"));
                dt.Columns.Add("Column2", Type.GetType("System.String"));
                dt.Columns.Add("Column3", Type.GetType("System.String"));
                dt.Columns.Add("Column4", Type.GetType("System.String"));
                dt.Columns.Add("Column5", Type.GetType("System.String"));
                dt.Columns.Add("Column6", Type.GetType("System.String"));
                dt.Columns.Add("Column7", Type.GetType("System.String"));
                dt.Columns.Add("Column8", Type.GetType("System.String"));
                DataRow dr = dt.NewRow();
                dr["Column1"] = (dt.Rows.Count + 1).ToString();
                dr["Column2"] = sEPC;
                dr["Column3"] = "1";
                dr["Column4"] = RSSI;
                dr["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                dr["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                dr["Column7"] = str_ant;
                dr["Column8"] = freqkhz + "";
                dt.Rows.Add(dr);
                comboBox_EPC.Items.Add(sEPC);
            }
            else
            {
                int index = epclist.IndexOf(sEPC);
                if (index == -1)
                {
                    NewCardNum++;
                    epclist.Add(sEPC);
                    DataRow dr2 = dt.NewRow();
                    dr2["Column1"] = (dt.Rows.Count + 1).ToString();
                    dr2["Column2"] = sEPC;
                    dr2["Column3"] = "1";
                    dr2["Column4"] = RSSI;
                    dr2["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                    dr2["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dr2["Column7"] = str_ant;
                    dr2["Column8"] = freqkhz + "";
                    dt.Rows.Add(dr2);
                    comboBox_EPC.Items.Add(sEPC);
                }
                else
                {
                    DataRow dr = dt.Rows[index];
                    int cnt = int.Parse(dr["Column3"].ToString());
                    cnt++;
                    dt.Rows[index]["Column3"] = cnt.ToString();
                    dt.Rows[index]["Column4"] = RSSI;
                    dt.Rows[index]["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                    dt.Rows[index]["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dt.Rows[index]["Column7"] = str_ant;
                    dt.Rows[index]["Column8"] = freqkhz + "";
                }
            }
        }
        private void updateTID(string sEPC, string RSSI, string str_ant, int phase_begin, int phase_end, int freqkhz)
        {
            if (tidlist.Count == 0)
            {
                NewCardNum++;
                tidlist.Add(sEPC);
                dt = dataGridView1.DataSource as DataTable;
                dt = new DataTable();
                dt.Columns.Add("Column1", Type.GetType("System.String"));
                dt.Columns.Add("Column2", Type.GetType("System.String"));
                dt.Columns.Add("Column3", Type.GetType("System.String"));
                dt.Columns.Add("Column4", Type.GetType("System.String"));
                dt.Columns.Add("Column5", Type.GetType("System.String"));
                dt.Columns.Add("Column6", Type.GetType("System.String"));
                dt.Columns.Add("Column7", Type.GetType("System.String"));
                dt.Columns.Add("Column8", Type.GetType("System.String"));
                DataRow dr = dt.NewRow();
                dr["Column1"] = (dt.Rows.Count + 1).ToString();
                dr["Column2"] = sEPC;
                dr["Column3"] = "1";
                dr["Column4"] = RSSI;
                dr["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                dr["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                dr["Column7"] = str_ant;
                dr["Column8"] = freqkhz + "";
                dt.Rows.Add(dr);
            }
            else
            {
                int index = tidlist.IndexOf(sEPC);
                if (index == -1)
                {
                    NewCardNum++;
                    tidlist.Add(sEPC);
                    DataRow dr2 = dt.NewRow();
                    dr2["Column1"] = (dt.Rows.Count + 1).ToString();
                    dr2["Column2"] = sEPC;
                    dr2["Column3"] = "1";
                    dr2["Column4"] = RSSI;
                    dr2["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                    dr2["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dr2["Column7"] = str_ant;
                    dr2["Column8"] = freqkhz + "";
                    dt.Rows.Add(dr2);
                }
                else
                {
                    DataRow dr = dt.Rows[index];
                    int cnt = int.Parse(dr["Column3"].ToString());
                    cnt++;
                    dt.Rows[index]["Column3"] = cnt.ToString();
                    dt.Rows[index]["Column4"] = RSSI;
                    dt.Rows[index]["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                    dt.Rows[index]["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dt.Rows[index]["Column7"] = str_ant;
                    dt.Rows[index]["Column8"] = freqkhz + "";
                }
            }
        }
        private void updateFastID(string sEPC, string RSSI, string str_ant, int phase_begin, int phase_end, int freqkhz)
        {
            if (epclist.Count == 0)
            {
                NewCardNum++;
                epclist.Add(sEPC);
                dt = dataGridView1.DataSource as DataTable;
                dt = new DataTable();
                dt.Columns.Add("Column1", Type.GetType("System.String"));
                dt.Columns.Add("Column2", Type.GetType("System.String"));
                dt.Columns.Add("Column3", Type.GetType("System.String"));
                dt.Columns.Add("Column4", Type.GetType("System.String"));
                dt.Columns.Add("Column5", Type.GetType("System.String"));
                dt.Columns.Add("Column6", Type.GetType("System.String"));
                dt.Columns.Add("Column7", Type.GetType("System.String"));
                dt.Columns.Add("Column8", Type.GetType("System.String"));
                DataRow dr = dt.NewRow();
                dr["Column1"] = (dt.Rows.Count + 1).ToString();
                dr["Column2"] = sEPC;
                dr["Column3"] = "1";
                dr["Column4"] = RSSI;
                dr["Column5"] = Convert.ToString(phase_begin * 0.087f);
                dr["Column6"] = Convert.ToString(phase_end * 0.087f);
                dr["Column7"] = str_ant;
                dr["Column8"] = freqkhz + "";
                dt.Rows.Add(dr);
                comboBox_EPC.Items.Add(sEPC);
            }
            else
            {
                int index = epclist.IndexOf(sEPC);
                if (index == -1)
                {
                    NewCardNum++;
                    epclist.Add(sEPC);
                    DataRow dr2 = dt.NewRow();
                    dr2["Column1"] = (dt.Rows.Count + 1).ToString();
                    dr2["Column2"] = sEPC;
                    dr2["Column3"] = "1";
                    dr2["Column4"] = RSSI;
                    dr2["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                    dr2["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dr2["Column7"] = str_ant;
                    dr2["Column8"] = freqkhz + "";
                    dt.Rows.Add(dr2);
                    comboBox_EPC.Items.Add(sEPC);
                }
                else
                {
                    DataRow dr = dt.Rows[index];
                    int cnt = int.Parse(dr["Column3"].ToString());
                    cnt++;
                    dt.Rows[index]["Column3"] = cnt.ToString();
                    dt.Rows[index]["Column4"] = RSSI;
                    dt.Rows[index]["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                    dt.Rows[index]["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dt.Rows[index]["Column7"] = str_ant;
                    dt.Rows[index]["Column8"] = freqkhz + "";
                }
            }
        }

        private void updateEPC_led(string sEPC, string RSSI, string str_ant, int phase_begin, int phase_end, int freqkhz)
        {
            if (epclist.Count == 0)
            {
                epclist.Add(sEPC);
                // checkedListBox1.Items.Add(sEPC);
                NewCardNum++;
                dt = dataGridView6.DataSource as DataTable;
                dt = new DataTable();
                DataGridViewCheckBoxColumn chkColumn = new DataGridViewCheckBoxColumn();
                chkColumn.Name = "Column1";
                chkColumn.HeaderText = "Column1";
                dataGridView6.Columns.Add(chkColumn);

                //dt.Columns.Add("Column1", Type.GetType("System.String"));
                dt.Columns.Add("Column2", Type.GetType("System.String"));
                dt.Columns.Add("Column3", Type.GetType("System.String"));
                dt.Columns.Add("Column4", Type.GetType("System.String"));
                dt.Columns.Add("Column5", Type.GetType("System.String"));
                dt.Columns.Add("Column6", Type.GetType("System.String"));
                dt.Columns.Add("Column7", Type.GetType("System.String"));
                dt.Columns.Add("Column8", Type.GetType("System.String"));
                DataRow dr = dt.NewRow();
                //dr["Column1"] = "false";
                dr["Column2"] = sEPC;
                dr["Column3"] = "1";
                dr["Column4"] = RSSI;
                dr["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                dr["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                dr["Column7"] = str_ant;
                dr["Column8"] = freqkhz + "";
                dt.Rows.Add(dr);
                lxLedControl10.Text = epclist.Count.ToString();
            }
            else
            {
                int index = epclist.IndexOf(sEPC);
                if (index == -1)
                {

                    NewCardNum++;
                    epclist.Add(sEPC);
                    //checkedListBox1.Items.Add(sEPC);
                    DataRow dr2 = dt.NewRow();
                    //dr2["Column1"] = "false";
                    dr2["Column2"] = sEPC;
                    dr2["Column3"] = "1";
                    dr2["Column4"] = RSSI;
                    dr2["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                    dr2["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dr2["Column7"] = str_ant;
                    dr2["Column8"] = freqkhz + "";
                    dt.Rows.Add(dr2);
                    lxLedControl10.Text = epclist.Count.ToString();
                }
                else
                {
                    DataRow dr = dt.Rows[index];
                    int cnt = int.Parse(dr["Column3"].ToString());
                    cnt++;
                    dt.Rows[index]["Column3"] = cnt.ToString();
                    dt.Rows[index]["Column4"] = RSSI;
                    dt.Rows[index]["Column5"] = String.Format("{0:N3}", phase_begin * 0.087f % 180);
                    dt.Rows[index]["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dt.Rows[index]["Column7"] = str_ant;
                    dt.Rows[index]["Column8"] = freqkhz + "";
                }
            }
        }


        private void updateEPC_TEMP(string sEPC, string RSSI, string str_ant, int phase_begin, int phase_end, int freqkhz)
        {
            if (epclist.Count == 0)
            {
                epclist.Add(sEPC);
                NewCardNum++;
                dt = dataGridView7.DataSource as DataTable;
                dt = new DataTable();

                dt.Columns.Add("Column1", Type.GetType("System.String"));
                dt.Columns.Add("Column2", Type.GetType("System.String"));
                dt.Columns.Add("Column3", Type.GetType("System.String"));
                dt.Columns.Add("Column4", Type.GetType("System.String"));
                dt.Columns.Add("Column5", Type.GetType("System.String"));
                dt.Columns.Add("Column6", Type.GetType("System.String"));
                dt.Columns.Add("Column7", Type.GetType("System.String"));
                DataRow dr = dt.NewRow();
                dr["Column1"] = (dt.Rows.Count + 1).ToString();
                dr["Column2"] = sEPC;
                dr["Column3"] = "1";
                dr["Column4"] = RSSI;
                dr["Column5"] = "";
                dr["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                dr["Column7"] = str_ant;
                dt.Rows.Add(dr);
                lxLedTemp.Text = epclist.Count.ToString();
            }
            else
            {
                int index = epclist.IndexOf(sEPC);
                if (index == -1)
                {

                    NewCardNum++;
                    epclist.Add(sEPC);
                    DataRow dr2 = dt.NewRow();
                    dr2["Column1"] = (dt.Rows.Count + 1).ToString();
                    dr2["Column2"] = sEPC;
                    dr2["Column3"] = "1";
                    dr2["Column4"] = RSSI;
                    dr2["Column5"] = "";
                    dr2["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dr2["Column7"] = str_ant;
                    dt.Rows.Add(dr2);
                    lxLedTemp.Text = epclist.Count.ToString();
                }
                else
                {
                    DataRow dr = dt.Rows[index];
                    int cnt = int.Parse(dr["Column3"].ToString());
                    cnt++;
                    dt.Rows[index]["Column3"] = cnt.ToString();
                    dt.Rows[index]["Column4"] = RSSI;
                    dt.Rows[index]["Column5"] = "";
                    dt.Rows[index]["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dt.Rows[index]["Column7"] = str_ant;
                }
            }
        }



        private void updateEPC_TRUTH(string sEPC, string RSSI, string str_ant, int phase_begin, int phase_end, int freqkhz)
        {
            if (epclist.Count == 0)
            {
                epclist.Add(sEPC);
                NewCardNum++;
                dt = dataGridView8.DataSource as DataTable;
                dt = new DataTable();

                dt.Columns.Add("Column1", Type.GetType("System.String"));
                dt.Columns.Add("Column2", Type.GetType("System.String"));
                dt.Columns.Add("Column3", Type.GetType("System.String"));
                dt.Columns.Add("Column4", Type.GetType("System.String"));
                dt.Columns.Add("Column5", Type.GetType("System.String"));
                dt.Columns.Add("Column6", Type.GetType("System.String"));
                dt.Columns.Add("Column7", Type.GetType("System.String"));
                DataRow dr = dt.NewRow();
                dr["Column1"] = (dt.Rows.Count + 1).ToString();
                dr["Column2"] = sEPC;
                dr["Column3"] = "1";
                dr["Column4"] = RSSI;
                dr["Column5"] = "";
                dr["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                dr["Column7"] = str_ant;
                dt.Rows.Add(dr);
                lxLedTruth.Text = epclist.Count.ToString();
            }
            else
            {
                int index = epclist.IndexOf(sEPC);
                if (index == -1)
                {

                    NewCardNum++;
                    epclist.Add(sEPC);
                    DataRow dr2 = dt.NewRow();
                    dr2["Column1"] = (dt.Rows.Count + 1).ToString();
                    dr2["Column2"] = sEPC;
                    dr2["Column3"] = "1";
                    dr2["Column4"] = RSSI;
                    dr2["Column5"] = "";
                    dr2["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dr2["Column7"] = str_ant;
                    dt.Rows.Add(dr2);
                    lxLedTruth.Text = epclist.Count.ToString();
                }
                else
                {
                    DataRow dr = dt.Rows[index];
                    int cnt = int.Parse(dr["Column3"].ToString());
                    cnt++;
                    dt.Rows[index]["Column3"] = cnt.ToString();
                    dt.Rows[index]["Column4"] = RSSI;
                    dt.Rows[index]["Column5"] = "";
                    dt.Rows[index]["Column6"] = String.Format("{0:N3}", phase_end * 0.087f % 180);
                    dt.Rows[index]["Column7"] = str_ant;
                }
            }
        }
        private delegate void WriteLogUnSafe(CustomControl.LogRichTextBox logRichTxt, string strLog, int nType);
        private void WriteLog(CustomControl.LogRichTextBox logRichTxt, string strLog, int nType)
        {
            if (this.InvokeRequired)
            {
                WriteLogUnSafe InvokeWriteLog = new WriteLogUnSafe(WriteLog);
                this.Invoke(InvokeWriteLog, new object[] { logRichTxt, strLog, nType });
            }
            else
            {

                if ((ckClearOperationRec.Checked) && (lrtxtLog.Lines.Length > 20))
                    lrtxtLog.Clear();
                if ((nType == 0) || (nType == 0x26) || (nType == 0x01) || (nType == 0x02) || (nType == 0xFB))
                {
                    logRichTxt.AppendTextEx(strLog, Color.Indigo);
                }
                else
                {
                    logRichTxt.AppendTextEx(strLog, Color.Red);
                }

                logRichTxt.Select(logRichTxt.TextLength, 0);
                logRichTxt.ScrollToCaret();
            }
        }
        /// <summary>
        /// 16进制数组字符串转换
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        #region
        public static byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }

        public static string ByteArrayToHexString(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
            return sb.ToString().ToUpper();

        }
        #endregion
        /// <summary>
        /// 错误代码
        /// </summary>
        /// <param name="cmdRet"></param>
        /// <returns></returns>
        #region 
        private string GetReturnCodeDesc(int cmdRet)
        {
            CultureInfo ci = Thread.CurrentThread.CurrentCulture;
            if (string.Equals(ci.Name, LangZh))
            {
                switch (cmdRet)
                {
                    case 0x00:
                    case 0x26:
                        return "操作成功";
                    case 0x01:
                        return "询查时间结束前返回";
                    case 0x02:
                        return "指定的询查时间溢出";
                    case 0x03:
                        return "本条消息之后，还有消息";
                    case 0x04:
                        return "读写模块存储空间已满";
                    case 0x05:
                        return "访问密码错误";
                    case 0x09:
                        return "销毁密码错误";
                    case 0x0a:
                        return "销毁密码不能为全0";
                    case 0x0b:
                        return "电子标签不支持该命令";
                    case 0x0c:
                        return "对该命令，访问密码不能为全0";
                    case 0x0d:
                        return "电子标签已经被设置了读保护，不能再次设置";
                    case 0x0e:
                        return "电子标签没有被设置读保护，不需要解锁";
                    case 0x10:
                        return "有字节空间被锁定，写入失败";
                    case 0x11:
                        return "不能锁定";
                    case 0x12:
                        return "已经锁定，不能再次锁定";
                    case 0x13:
                        return "参数保存失败,但设置的值在读写模块断电前有效";
                    case 0x14:
                        return "无法调整";
                    case 0x15:
                        return "询查时间结束前返回";
                    case 0x16:
                        return "指定的询查时间溢出";
                    case 0x17:
                        return "本条消息之后，还有消息";
                    case 0x18:
                        return "读写模块存储空间已满";
                    case 0x19:
                        return "电子不支持该命令或者访问密码不能为0";
                    case 0x1A:
                        return "标签自定义功能执行错误";
                    case 0xF8:
                        return "检测天线错误";
                    case 0xF9:
                        return "命令执行出错";
                    case 0xFA:
                        return "有电子标签，但通信不畅，无法操作";
                    case 0xFB:
                        return "无电子标签可操作";
                    case 0xFC:
                        return "电子标签返回错误代码";
                    case 0xFD:
                        return "命令长度错误";
                    case 0xFE:
                        return "不合法的命令";
                    case 0xFF:
                        return "参数错误";
                    case 0x30:
                        return "通讯错误";
                    case 0x31:
                        return "CRC校验错误";
                    case 0x32:
                        return "返回数据长度有错误";
                    case 0x33:
                        return "通讯繁忙，设备正在执行其他指令";
                    case 0x34:
                        return "繁忙，指令正在执行";
                    case 0x35:
                        return "端口已打开";
                    case 0x36:
                        return "端口已关闭";
                    case 0x37:
                        return "无效句柄";
                    case 0x38:
                        return "无效端口";
                    case 0xEE:
                        return "命令代码错误";
                    default:
                        return "";
                }
            }
            else
            {
                switch (cmdRet)
                {
                    case 0x00:
                    case 0x26:
                        return "operation succeeded";
                    case 0x01:
                        return "returns before the end of the inventory time";
                    case 0x02:
                        return "specified inventory time overflow";
                    case 0x03:
                        return "after this message, there is a message";
                    case 0x04:
                        return "read and write module storage is full";
                    case 0x05:
                        return "access password error";
                    case 0x09:
                        return "kill password error";
                    case 0x0a:
                        return "kill password cannot be all 0";
                    case 0x0b:
                        return "the tag does not support this command";
                    case 0x0c:
                        return "the access password cannot be all 0 for this command";
                    case 0x0d:
                        return "the tag has been set to read protection and cannot be set again";
                    case 0x0e:
                        return "the tag is not set to read protection and does not need to be unlocked";
                    case 0x10:
                        return "there are some byte locked, write failed";
                    case 0x11:
                        return "cannot lock";
                    case 0x12:
                        return "already locked, can't lock again";
                    case 0x13:
                        return "parameter save failed, but the set value is valid before the read/write module is powered off";
                    case 0x14:
                        return "cannot adjust";
                    case 0x15:
                        return "returns before the end of the inventory time";
                    case 0x16:
                        return "specified inventory time overflow";
                    case 0x17:
                        return "after this message, there is a message";
                    case 0x18:
                        return "read and write module storage is full";
                    case 0x19:
                        return "tag does not support this command or the access password cannot be 0";
                    case 0x1A:
                        return "tag custom function execution error";
                    case 0xF8:
                        return "detect antenna error";
                    case 0xF9:
                        return "command execution error";
                    case 0xFA:
                        return "there is a tag, but the communication is not smooth and cannot be operated";
                    case 0xFB:
                        return "no tag is operational";
                    case 0xFC:
                        return "tag returns error code";
                    case 0xFD:
                        return "command length error";
                    case 0xFE:
                        return "unlawful command";
                    case 0xFF:
                        return "parameter error";
                    case 0x30:
                        return "communication error";
                    case 0x31:
                        return "CRC check error";
                    case 0x32:
                        return "there is an error in returning the data length";
                    case 0x33:
                        return "the communication is busy, the device is executing other instructions";
                    case 0x34:
                        return "busy, the instruction is being executed";
                    case 0x35:
                        return "port is open";
                    case 0x36:
                        return "port is closed";
                    case 0x37:
                        return "invalid handle";
                    case 0x38:
                        return "invalid port";
                    case 0xEE:
                        return "command code error";
                    default:
                        return "";
                }
            }
        }
        private string GetErrorCodeDesc(int cmdRet)
        {
            CultureInfo ci = Thread.CurrentThread.CurrentCulture;
            if (string.Equals(ci.Name, LangZh))
            {
                switch (cmdRet)
                {
                    case 0x00:
                        return "其它错误";
                    case 0x03:
                        return "存储器超限或不被支持的PC值";
                    case 0x04:
                        return "存储器锁定";
                    case 0x0b:
                        return "电源不足";
                    case 0x0f:
                        return "非特定错误";
                    default:
                        return "";
                }
            }
            else
            {
                switch (cmdRet)
                {
                    case 0x00:
                        return "Other errors";
                    case 0x03:
                        return "memory overrun or unsupported PC value";
                    case 0x04:
                        return "memory locked";
                    case 0x0b:
                        return "low power";
                    case 0x0f:
                        return "non-specific error";
                    default:
                        return "";
                }
            }
        }
        #endregion

        private void DisabledForm()
        {
            ////应答模式下
            lxLedControl1.Text = "0";
            lxLedControl2.Text = "0";
            lxLedControl3.Text = "0";
            lxLedControl4.Text = "0";
            lxLedControl5.Text = "0";
            dataGridView1.DataSource = null;
            comboBox_EPC.Items.Clear();
            text_RDVersion.Text = "";
            text_MDVersion.Text = "";
            text_Serial.Text = "";
            timer_answer.Enabled = false;
            btIventoryG2.Text = ResourceCulture.GetString("hint_button_start"); 
            chk_phase.Enabled = false;
            panel2.Enabled = false;
            panel4.Enabled = false;
            panel5.Enabled = false;
            panel10.Enabled = false;
            gpb_address.Enabled = false;
            gpb_antconfig.Enabled = false;
            gpb_baud.Enabled = false;
            gpb_GPIO.Enabled = false;
            gpb_beep.Enabled = false;
            gpb_MDVersion.Enabled = false;
            gpb_RDVersion.Enabled = false;
            gpb_checkant.Enabled = false;
            gpb_DBM.Enabled = false;
            gpb_Serial.Enabled = false;
            gpb_Relay.Enabled = false;
            gpb_OutputRep.Enabled = false;
            gpb_Freq.Enabled = false;
            btDefault.Enabled = false;
            btGetInformation.Enabled = false;
            btFlashROM.Enabled = false;
            group_maxtime.Enabled = false;
            gbp_wpower.Enabled = false;
            gbp_Retry.Enabled = false;
            gbCmdTemperature.Enabled = false;
            gbReturnLoss.Enabled = false;
            groupBox45.Enabled = false;
            panel11.Enabled = false;
            panel13.Enabled = false;

            panel1.Enabled = false;
            panel14.Enabled = false;
            groupBox62.Enabled = false;

            panel7.Enabled = false;
            panel15.Enabled = false;
            panel16.Enabled = false;
            panel17.Enabled = false;
        }

        private void EnabledForm()
        {
            chk_phase.Enabled = true;
            panel2.Enabled = true;
            panel4.Enabled = true;
            panel5.Enabled = true;
            panel10.Enabled = true;
            gpb_address.Enabled = true;
            gpb_antconfig.Enabled = true;
            gpb_baud.Enabled = true;
            gpb_GPIO.Enabled = true;
            gpb_beep.Enabled = true;
            gpb_MDVersion.Enabled = true;
            gpb_RDVersion.Enabled = true;
            gpb_checkant.Enabled = true;
            gpb_DBM.Enabled = true;
            gpb_Serial.Enabled = true;
            gpb_Relay.Enabled = true;
            gpb_OutputRep.Enabled = true;
            gpb_Freq.Enabled = true;
            btDefault.Enabled = true;
            btGetInformation.Enabled = true;
            btFlashROM.Enabled = true;
            group_maxtime.Enabled = true;
            gbp_wpower.Enabled = true;
            gbp_Retry.Enabled = true;
            gbCmdTemperature.Enabled = true;
            gbReturnLoss.Enabled = true;
            groupBox45.Enabled = true;
            panel11.Enabled = true;
            panel13.Enabled = true;

            panel1.Enabled = true;
            panel14.Enabled = true;
            groupBox62.Enabled = true;

            panel7.Enabled = true;
            panel15.Enabled = true;
            panel16.Enabled = true;
            panel17.Enabled = true;
        }

        private void rb_rs232_CheckedChanged(object sender, EventArgs e)
        {
            if (rb_rs232.Checked)
            {
                if ((frmcomportindex > 0) && (frmcomportindex < 256))
                {
                    if (frmcomportindex > 0)
                        fCmdRet = RWDev.CloseNetPort(frmcomportindex);
                    if (fCmdRet == 0)
                    {
                        frmcomportindex = -1;
                        btConnectTcp.Enabled = true;
                        btDisConnectTcp.Enabled = false;
                        DisabledForm();
                        btConnectTcp.ForeColor = Color.Indigo;
                        btDisConnectTcp.ForeColor = Color.Black;
                        SetButtonBold(btConnectTcp);
                        SetButtonBold(btDisConnectTcp);
                    }
                    if (fCmdRet != 0)
                    {
                        string strLog = ResourceCulture.GetString("log_tcp_close_failed") +":" + GetReturnCodeDesc(fCmdRet);
                        WriteLog(lrtxtLog, strLog, 1);

                        return;
                    }
                    else
                    {
                        string strLog = ResourceCulture.GetString("log_tcp_close_success");
                        WriteLog(lrtxtLog, strLog, 0);
                    }
                }

                gpb_rs232.Enabled = true;
                btDisConnect232.Enabled = false;
                //设置按钮字体颜色
                btConnect232.ForeColor = Color.Indigo;
                SetButtonBold(btConnect232);
                if (btConnectTcp.Font.Bold)
                {
                    SetButtonBold(btConnectTcp);
                }
                gpb_tcp.Enabled = false;
            }
        }

        private void rb_tcp_CheckedChanged(object sender, EventArgs e)
        {
            if (rb_tcp.Checked)
            {
                if ((frmcomportindex > 0) && (frmcomportindex < 256))
                {
                    if (frmcomportindex > 0)
                        fCmdRet = RWDev.CloseSpecComPort(frmcomportindex);
                    if (fCmdRet == 0)
                    {
                        frmcomportindex = -1;
                        DisabledForm();
                        btConnect232.Enabled = true;
                        btDisConnect232.Enabled = false;

                        btConnect232.ForeColor = Color.Indigo;
                        btDisConnect232.ForeColor = Color.Black;
                        SetButtonBold(btConnect232);
                        SetButtonBold(btDisConnect232);
                    }
                    if (fCmdRet != 0)
                    {
                        string strLog = ResourceCulture.GetString("log_com_close_failed") +":" + GetReturnCodeDesc(fCmdRet);
                        WriteLog(lrtxtLog, strLog, 1);
                        return;
                    }
                    else
                    {
                        string strLog = ResourceCulture.GetString("log_com_close_success");
                        WriteLog(lrtxtLog, strLog, 0);
                    }
                }
                gpb_tcp.Enabled = true;
                btDisConnectTcp.Enabled = false;

                //设置按钮字体颜色
                btConnectTcp.ForeColor = Color.Indigo;
                if (btConnect232.Font.Bold)
                {
                    SetButtonBold(btConnect232);
                }
                SetButtonBold(btConnectTcp);
                gpb_rs232.Enabled = false;
            }
        }
        private void SetButtonBold(Button btnBold)
        {
            Font oldFont = btnBold.Font;
            Font newFont = new Font(oldFont, oldFont.Style ^ FontStyle.Bold);
            btnBold.Font = newFont;
        }

        private void SetRadioButtonBold(CheckBox ckBold)
        {
            Font oldFont = ckBold.Font;
            Font newFont = new Font(oldFont, oldFont.Style ^ FontStyle.Bold);
            ckBold.Font = newFont;
        }

        public static string[] GetNetWorkInfo()
        {
            List<string> netWorkList = new List<string>();
            NetworkInterface[] NetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();  //获取所有的网络接口
            foreach (NetworkInterface NetworkIntf in NetworkInterfaces)                         //针对每张网卡
            {
                IPInterfaceProperties IPInterfaceProperties = NetworkIntf.GetIPProperties();    //获取描述此网络接口的配置的对象
                UnicastIPAddressInformationCollection UnicastIPAddressInformationCollection = IPInterfaceProperties.UnicastAddresses;//获取分配给此接口的单播地址
                foreach (UnicastIPAddressInformation UnicastIPAddressInformation in UnicastIPAddressInformationCollection) //针对每个IP
                {
                    if (UnicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)//IPv4
                    {
                        string IP = UnicastIPAddressInformation.Address.ToString();//获取本机IP
                        if (IP != "127.0.0.1")//不是本地IP
                        {
                            if (NetworkIntf.OperationalStatus == OperationalStatus.Up)//网卡已连接
                            {
                                netWorkList.Add(IP + ":" + NetworkIntf.Name + ":" + NetworkIntf.Description);
                            }
                        }
                    }
                }
            }
            return netWorkList.ToArray();
        }

   
        private void LoadConfig()
        {
            lang = "";
            try
            {
                string ipAddr = Config.GetINI("SysConfig", "IPAddress", "", iniPath);
                string Port = Config.GetINI("SysConfig", "Port", "", iniPath);
                lang = Config.GetINI("SysConfig", "Language", "", iniPath);
                tb_Port.Text = Port;
                ipServerIP.Text = ipAddr;
                if (string.Equals(lang, LangZh))
                {
                    radio_ch.Checked = true;
                }
                else
                {
                    radio_en.Checked = true;
                }
            }
            catch (Exception)
            {
                MessageBox.Show(ResourceCulture.GetString("err_load_xml"));
            }
            ResourceCulture.SetLang(lang, this, typeof(Form1));
            SetListViewHeaderGlobalization();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadConfig();
            string[] network = GetNetWorkInfo();
            for (int m = 0; m < network.Length; m++)
            {
                comboBox11.Items.Add(network[m]);
            }
            if (network!=null && network.Length > 0)
                comboBox11.SelectedIndex = 0;
            gpb_rs232.Enabled = false;
            gpb_tcp.Enabled = false;
            rb_rs232.Checked = true;
            ComboBox_COM.SelectedIndex = 0;
            ComboBox_baud2.SelectedIndex = 3;
            com_Q.SelectedIndex = 4;
            com_Target.SelectedIndex = 0;
            int i = 0;
            for (i = 0x00; i <= 0xff; i++)
            {
                com_scantime.Items.Add(i + "*100ms");
                comboBox_maxtime.Items.Add(i + "*100ms");
                cbb_rf_delaytime.Items.Add(i + "*100ms");
                cbb_cmd_interval.Items.Add(i + "*100ms");
                comboBox9.Items.Add(i + "*10ms");
                comboBox18.Items.Add(i + "");
                cbb_ant_dwelltime.Items.Add(i + "*100ms");
                cbb_relaytime.Items.Add(i + "*100ms");
            }
            cbb_relaytime.SelectedIndex = 30;
            cbb_ant_dwelltime.SelectedIndex = 0;
            comboBox19.SelectedIndex = 0;
            comboBox9.SelectedIndex = 30;
            comboBox18.SelectedIndex = 0;
            cbb_cmd_interval.SelectedIndex = 0;
            cbb_rf_delaytime.SelectedIndex = 20;
            com_scantime.SelectedIndex = 10;
            comboBox_maxtime.SelectedIndex = 0;
            com_S.SelectedIndex = 6;
            DisabledForm();
            radioButton_band2.Checked = true;
            ComboBox_baud.SelectedIndex = 3;
            ComboBox_PowerDbm.SelectedIndex = 30;
            com_acQ.SelectedIndex = 6;
            com_acS.SelectedIndex = 0;
            comboBox_intervalT.SelectedIndex = 0;
            for (i = 0; i < 256; i++)
            {
                comboBox_trigger.Items.Add(Convert.ToString(i));
                comboBox_RespTime.Items.Add(Convert.ToString(i));
                ComboBox_RelayTime.Items.Add(Convert.ToString(i));
            }
            for (i = 1; i < 256; i++)
            {
                
                comboBox10.Items.Add(i + "*10us");
                comboBox16.Items.Add(i + "*100us");
            }
            for (i = 2; i < 256; i++)
            {
                cbb_dwell.Items.Add(Convert.ToString(i) + "*100ms");
            }
            comboBox10.SelectedIndex = 9;
            comboBox16.SelectedIndex = 14;
            cbb_dwell.SelectedIndex = 0;
            ComboBox_RelayTime.SelectedIndex = 30;
            cbb_relayAction.SelectedIndex = 1;
            comboBox_trigger.SelectedIndex = 0;
            comboBox_Resp.SelectedIndex = 1;
            comboBox_RespTime.SelectedIndex = 0;
            comboBox_mode.SelectedIndex = 0;
           
            com_wpower.SelectedIndex = 30;
            com_retrytimes.SelectedIndex = 3;
            com_MixMem.SelectedIndex = 2;
            cbbAnt.SelectedIndex = 0;


            com_queryInter.SelectedIndex = 0;
            cbb_add.SelectedIndex = 4;

            for (i = 1; i < 62; i++)
            {
                comboBox6.Items.Add(i);
            }
            comboBox1.SelectedIndex = 2;

            cbb_led_q.SelectedIndex = 6;
            cbb_led_s.SelectedIndex = 2;
            cbb_led_t.SelectedIndex = 0;

            comboBox8.SelectedIndex = 4;
            comboBox7.SelectedIndex = 2;
            comboBox5.SelectedIndex = 0;

            comboBox15.SelectedIndex = 4;
            comboBox14.SelectedIndex = 2;
            comboBox13.SelectedIndex = 0;

            comboBox17.SelectedIndex = 0;

            com_contype.SelectedIndex = 0;
            cbb_Reconnect.SelectedIndex = 0;
            wifi_com_contype.SelectedIndex = 0;
            wifi_cbb_Reconnect.SelectedIndex = 0;
            cbb_wifi_keepalive_en.SelectedIndex = 1;
            cbb_keepalive_en.SelectedIndex = 1;
            com_wg_type.SelectedIndex = 0;
            cbb_output.SelectedIndex = 0;
            cbb_matchlength.SelectedIndex = 6;

            tabControl2.TabPages.Remove(tabPage17);
            tabControl2.TabPages.Remove(tabPage18);
            tabControl2.TabPages.Remove(tabPage19);
            
            Maintab.TabPages.Remove(Main_Page3);
        }

        private void btConnect232_Click(object sender, EventArgs e)
        {
            int portNum = ComboBox_COM.SelectedIndex + 1;
            int FrmPortIndex = 0;
            string strException = string.Empty;
            fBaud = Convert.ToByte(ComboBox_baud2.SelectedIndex);
            if (fBaud > 2)
                fBaud = Convert.ToByte(fBaud + 2);
            fComAdr = 255;//广播地址打开设备
            fCmdRet = RWDev.OpenComPort(portNum, ref fComAdr, fBaud, ref FrmPortIndex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_connect_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
                return;
            }
            else
            {
                frmcomportindex = FrmPortIndex;
                string strLog = string.Format(ResourceCulture.GetString("log_connect_reader"), ComboBox_COM.Text, ComboBox_baud2.Text);
                WriteLog(lrtxtLog, strLog, 0);
            }
            EnabledForm();
            btConnect232.Enabled = false;
            btDisConnect232.Enabled = true;
            //设置按钮字体颜色
            btConnect232.ForeColor = Color.Black;
            btDisConnect232.ForeColor = Color.Indigo;
            SetButtonBold(btConnect232);
            SetButtonBold(btDisConnect232);
            btGetInformation_Click(null, null);
            if (FrmPortIndex > 0)
                RWDev.InitRFIDCallBack(elegateRFIDCallBack, true, FrmPortIndex);
        }

        private void btDisConnect232_Click(object sender, EventArgs e)
        {
            if (frmcomportindex > 0)
                fCmdRet = RWDev.CloseSpecComPort(frmcomportindex);
            if (fCmdRet == 0)
            {
                frmcomportindex = -1;
                DisabledForm();
                btConnect232.Enabled = true;
                btDisConnect232.Enabled = false;

                btConnect232.ForeColor = Color.Indigo;
                btDisConnect232.ForeColor = Color.Black;
                SetButtonBold(btConnect232);
                SetButtonBold(btDisConnect232);
            }
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_com_close_failed") + ":" + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);

                return;
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_com_close_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btDisConnectTcp_Click(object sender, EventArgs e)
        {
            if (frmcomportindex > 0)
                fCmdRet = RWDev.CloseNetPort(frmcomportindex);
            if (fCmdRet == 0)
            {
                frmcomportindex = -1;
                btConnectTcp.Enabled = true;
                btDisConnectTcp.Enabled = false;
                DisabledForm();
                btConnectTcp.ForeColor = Color.Indigo;
                btDisConnectTcp.ForeColor = Color.Black;
                SetButtonBold(btConnectTcp);
                SetButtonBold(btDisConnectTcp);
            }
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_tcp_close_failed") + ":" + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);

                return;
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_tcp_close_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btConnectTcp_Click(object sender, EventArgs e)
        {
            try
            {
                string strException = string.Empty;
                string ipAddress = ipServerIP.IpAddressStr;
                int nPort = Convert.ToInt32(tb_Port.Text);
                fComAdr = 255;
                int FrmPortIndex = 0;
                fCmdRet = RWDev.OpenNetPort(nPort, ipAddress, ref fComAdr, ref FrmPortIndex);
                if (fCmdRet != 0)
                {
                    string strLog = ResourceCulture.GetString("log_connect_failed") + GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);

                    return;
                }
                else
                {
                    frmcomportindex = FrmPortIndex;
                    string strLog = string.Format(ResourceCulture.GetString("log_connect_reader"), ipAddress, nPort.ToString());
                    WriteLog(lrtxtLog, strLog, 0);
                }

                EnabledForm();
                btConnectTcp.Enabled = false;
                btDisConnectTcp.Enabled = true;

                //设置按钮字体颜色
                btConnectTcp.ForeColor = Color.Black;
                btDisConnectTcp.ForeColor = Color.Indigo;
                SetButtonBold(btConnectTcp);
                SetButtonBold(btDisConnectTcp);
                btGetInformation_Click(null, null);//获取读写器信息
                if (FrmPortIndex > 0)
                    RWDev.InitRFIDCallBack(elegateRFIDCallBack, true, FrmPortIndex);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btFlashCl_Click(object sender, EventArgs e)
        {
            ////应答模式下刷屏
            if (tabControl2.SelectedTab == tabPage_answer)
            {
                lxLedControl1.Text = "0";
                lxLedControl2.Text = "0";
                lxLedControl3.Text = "0";
                lxLedControl4.Text = "0";
                lxLedControl5.Text = "0";
                lxLedControl6.Text = "0";
                epclist.Clear();
                tidlist.Clear();
                dataGridView1.DataSource = null;
            }
            if (tabControl2.SelectedTab == tabPage17)
            {
                
                epclist.Clear();
                tidlist.Clear();
                dataGridView6.Columns.Clear();
                dataGridView6.DataSource = null;
                lxLedControl10.Text = "0";
            }

          
            ////主动模式刷屏
            if (tabControl2.SelectedTab == tabPage_Realtime)
            {
                lxLed_Mtag.Text = "0";
                lxLed_Mtime.Text = "0";
                total_time = System.Environment.TickCount;
                dataGridView4.Rows.Clear();

            }
           
            ////6B标签刷屏
            if (Maintab.SelectedTab == Main_Page3)
            {
                text_R6B.Text = "";
                text_6BUID.Text = "";
                text_Statu6B.Text = "";
            }
            ////应答模式下刷屏

           
            if (tabControl3.SelectedTab == tabPage8)//TCP 服务器
            {
                stcprecv.Clear();
            }
            if (tabControl3.SelectedTab == tabPage9)//TCP 客户端
            {
                ctctrecv.Clear();
                ctctsend.Text = "";
            }
            total_tagnum = 0;
            total_time = System.Environment.TickCount;
            comboBox_EPC.Items.Clear();
            lrtxtLog.Clear();

        }
        byte[] antlist = new byte[16];
        private volatile bool fIsInventoryScan = false;
        private volatile bool toStopThread = false;
        private volatile bool reflasg = false;
        private Thread mythread = null;

        byte[] ReadAdr = new byte[2];
        byte[] Psd = new byte[4];
        byte ReadLen = 0;
        byte ReadMem = 0;
        byte RF_Profile = 0;
        byte Profile = 0;
        int readMode = 0;
        int tagrate = 0;
        private void btIventoryG2_Click(object sender, EventArgs e)
        {
            if ((text_readadr.Text.Length != 4) || (text_readLen.Text.Length != 2) || (text_readpsd.Text.Length != 8))
            {
                return;
            }

            if (btIventoryG2.Text == ResourceCulture.GetString("btn_inventory_start"))
            {
                if (rb_mix.Checked)
                {
                    ReadMem = (byte)com_MixMem.SelectedIndex;
                    ReadAdr = HexStringToByteArray(text_readadr.Text);
                    ReadLen = Convert.ToByte(text_readLen.Text, 16);
                    Psd = HexStringToByteArray(text_readpsd.Text);
                }
                lxLedControl1.Text = "0";
                lxLedControl2.Text = "0";
                lxLedControl3.Text = "0";
                lxLedControl4.Text = "0";
                lxLedControl5.Text = "0";
                lxLedControl6.Text = "0";
                reflasg = false;
                epclist.Clear();
                tidlist.Clear();
                curList.Clear();
                dataGridView1.DataSource = null;
                lrtxtLog.Clear();
                comboBox_EPC.Items.Clear();
                text_epc.Text = "";
                AA_times = 0;
      
                Scantime = Convert.ToByte(com_scantime.SelectedIndex);
                if (checkBox_rate.Checked)
                    Qvalue = Convert.ToByte(com_Q.SelectedIndex | 0x80);
                else
                    Qvalue = Convert.ToByte(com_Q.SelectedIndex);

                if (ModeType == 2)
                {
                    Profile = (byte)(RF_Profile | 0xC0);
                    fCmdRet = RWDev.SetProfile(ref fComAdr, ref Profile, frmcomportindex);
                }

                if (com_S.SelectedIndex == 4)
                {
                    readMode = 255;
                }
                else if (com_S.SelectedIndex < 4)
                {
                    readMode = Convert.ToByte(com_S.SelectedIndex);
                }
                else if (com_S.SelectedIndex == 5)
                {
                    readMode = 254;
                }
                else if (com_S.SelectedIndex == 6)
                {
                    readMode = 253;
                    
                }

                if (rb_epc.Checked)
                {
                    TIDFlag = 0;
                    scanType = 0;
                }
                else if (rb_tid.Checked)
                {
                    TIDFlag = 1;
                    tidAddr = (byte)(Convert.ToInt32(text_readadr.Text, 16) & 0x00FF);
                    tidLen = Convert.ToByte(text_readLen.Text, 16);
                    scanType = 1;
                }
                else if (rb_fastid.Checked)
                {
                    TIDFlag = 0;
                    Qvalue = Convert.ToByte(com_Q.SelectedIndex | 0x20);
                    scanType = 2;
                }
                else
                {
                    scanType = 3;
                }

                if (check_phase.Checked) Qvalue |= 0x10;

                total_tagnum = 0;
                targettimes = Convert.ToInt32(text_target.Text);
                total_time = System.Environment.TickCount;
                fIsInventoryScan = false;
                btIventoryG2.BackColor = Color.Indigo;
                btIventoryG2.Text = ResourceCulture.GetString("btn_inventory_stop");
                Array.Clear(antlist, 0, 16);
                int SelectAntenna = 0;
                if (check_ant1.Checked)
                {
                    antlist[0] = 1;
                    InAnt = 0x80;
                    SelectAntenna |= 0x0001;
                }

                if (check_ant2.Checked)
                {
                    antlist[1] = 1;
                    InAnt = 0x81;
                    SelectAntenna |= 0x0002;
                }
                
                PresetTarget(readMode,SelectAntenna);

                Target = (byte)com_Target.SelectedIndex;
                toStopThread = false;
                if (fIsInventoryScan == false)
                {
                    mythread = new Thread(new ThreadStart(inventory));
                    mythread.IsBackground = true;
                    mythread.Start();
                    timer_answer.Enabled = true;
                }
                rb_mix.Enabled = false;
                rb_epc.Enabled = false;
                rb_tid.Enabled = false;
                rb_fastid.Enabled = false;
            }
            else
            {
                RWDev.StopImmediately(ref fComAdr, frmcomportindex);
                toStopThread = true;
                btIventoryG2.Enabled = false;
                btIventoryG2.BackColor = Color.Transparent;
                btIventoryG2.Text = ResourceCulture.GetString("btn_inventory_stoping"); ;
            }
        }

        
        public void PresetTarget(int readMode, int SelectAntenna)
        {
            byte CurSession = 0;
            if (readMode > 0)
            {
                byte MaskMem = 1;
                byte[] MaskAdr = new byte[2];
                byte MaskLen = 0;
                byte[] MaskData = new byte[100];

                if ((readMode == 254 || readMode==253)&& (ModeType==2))
                {
                    if (Session == 254)
                    {
                        Session = 253;
                        CurSession = 2;
                    }
                    else
                    {
                        Session = 254;
                        CurSession = 3;
                    }

                    if (readMode==253)
                        Profile = 0xC1;
                    else
                        Profile = 0xC5;
                    fCmdRet = RWDev.SetProfile(ref fComAdr, ref Profile, frmcomportindex);
                   
                }
                else if (readMode==255)
                {
                    CurSession = (byte)2;
                    Session = (byte)readMode;
                }
                else if (readMode < 4)
                {
                    CurSession = (byte)readMode;
                    Session = CurSession;
                }
                
                for (int m = 0; m < 4; m++)
                {
                    fCmdRet = RWDev.SelectCMDByAntenna(ref fComAdr, SelectAntenna, AntennaNum, CurSession, 0, MaskMem, MaskAdr, MaskLen, MaskData, 0, frmcomportindex);
                    Thread.Sleep(5);
                }
            }
            else
            {
                Session = (byte)readMode;
            }

            
        }

        #region ///EPC或TID查询
        private void flash_G2()
        {
            byte Ant = 0;
            int TagNum = 0;
            int Totallen = 0;
            byte[] EPC = new byte[50000];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            byte MaskFlag = 0;
            MaskFlag = 0;
            int cbtime = System.Environment.TickCount;
            CardNum = 0;
            tagrate = 0;
            NewCardNum = 0;
            fCmdRet = RWDev.Inventory_G2(ref fComAdr, Qvalue, Session, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, tidAddr, tidLen, TIDFlag, Target, InAnt, Scantime, FastFlag, EPC, ref Ant, ref Totallen, ref TagNum, frmcomportindex);
            int cmdTime = System.Environment.TickCount - cbtime;//命令时间
            if ((fCmdRet != 0x01) && (fCmdRet != 0x02) && (fCmdRet != 0xF8) && (fCmdRet != 0xF9) && (fCmdRet != 0xEE) && (fCmdRet != 0xFF))
            {
                if (rb_tcp.Checked)
                {
                    if ((frmcomportindex > 0) && (frmcomportindex < 256))
                    {
                        fCmdRet = RWDev.CloseNetPort(frmcomportindex);
                        if (fCmdRet == 0) frmcomportindex = -1;
                        Thread.Sleep(1000);
                    }
                    fComAdr = 255;
                    string ipAddress = ipServerIP.IpAddressStr;
                    int nPort = Convert.ToInt32(tb_Port.Text);
                    fCmdRet = RWDev.OpenNetPort(nPort, ipAddress, ref fComAdr, ref frmcomportindex);
                    if (fCmdRet == 0)
                    {
                        if (frmcomportindex > 0)
                            RWDev.InitRFIDCallBack(elegateRFIDCallBack, true, frmcomportindex);
                    }
                }
            }
            if (fCmdRet == 0x30)
            {
                CardNum = 0;
            }
            if (CardNum == 0)
            {
                if (Session > 1)
                    AA_times = AA_times + 1;//没有得到标签只更新状态栏
            }
            else
            {
                if ((ModeType == 2) && (readMode == 253 || readMode == 254) && (NewCardNum == 0))
                    AA_times = AA_times + 1;//没有得到新标签
                else
                    AA_times = 0;
            }
            if ((fCmdRet == 1) || (fCmdRet == 2) || (fCmdRet == 0xFB) || (fCmdRet == 0x26))
            {
                if (cmdTime > CommunicationTime)
                    cmdTime = cmdTime - CommunicationTime;//减去通讯时间等于标签的实际时间
                if (cmdTime > 0)
                {
                    tagrate = (CardNum * 1000) / cmdTime;//速度等于张数/时间
                    IntPtr ptrWnd = IntPtr.Zero;
                    ptrWnd = FindWindow(null, "UHFReader DS7 Demo V1.1");
                    if (ptrWnd != IntPtr.Zero)         // 检查当前统计窗口是否打开
                    {
                        string para = tagrate.ToString() + "," + total_tagnum.ToString() + "," + cmdTime.ToString();
                        SendMessage(ptrWnd, WM_SENDTAGSTAT, IntPtr.Zero, para);
                    }
                }

            }
            IntPtr ptrWnd1 = IntPtr.Zero;
            ptrWnd1 = FindWindow(null, "UHFReader DS7 Demo V1.1");
            if (ptrWnd1 != IntPtr.Zero)         // 检查当前统计窗口是否打开
            {
                string para = fCmdRet.ToString();
                SendMessage(ptrWnd1, WM_SENDSTATU, IntPtr.Zero, para);
            }
            ptrWnd1 = IntPtr.Zero;
        }
        #endregion

        #region ///混合查询
        private void flashmix_G2()
        {
            byte Ant = 0;
            int TagNum = 0;
            int Totallen = 0;
            byte[] EPC = new byte[50000];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            byte MaskFlag = 0;
            MaskFlag = 0;
            int cbtime = System.Environment.TickCount;
            CardNum = 0;
            NewCardNum = 0;
            fCmdRet = RWDev.InventoryMix_G2(ref fComAdr, Qvalue, Session, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, ReadMem, ReadAdr, ReadLen, Psd, Target, InAnt, Scantime, FastFlag, EPC, ref Ant, ref Totallen, ref TagNum, frmcomportindex);
            int cmdTime = System.Environment.TickCount - cbtime;//命令时间
            if ((fCmdRet != 0x01) && (fCmdRet != 0x02) && (fCmdRet != 0xF8) && (fCmdRet != 0xF9) && (fCmdRet != 0xEE) && (fCmdRet != 0xFF))
            {
                if (rb_tcp.Checked)
                {
                    if ((frmcomportindex > 0) && (frmcomportindex < 256))
                    {
                        fCmdRet = RWDev.CloseNetPort(frmcomportindex);
                        if (fCmdRet == 0) frmcomportindex = -1;
                        Thread.Sleep(1000);
                    }
                    fComAdr = 255;
                    string ipAddress = ipServerIP.IpAddressStr;
                    int nPort = Convert.ToInt32(tb_Port.Text);
                    fCmdRet = RWDev.OpenNetPort(nPort, ipAddress, ref fComAdr, ref frmcomportindex);
                    if (fCmdRet == 0)
                    {
                        if (frmcomportindex > 0)
                            RWDev.InitRFIDCallBack(elegateRFIDCallBack, true, frmcomportindex);
                    }
                }
            }
            NewCardNum = CardNum;
            if (CardNum == 0)
            {
                if (Session > 1)
                    AA_times = AA_times + 1;//没有得到标签只更新状态栏
            }
            else
                AA_times = 0;
            if ((fCmdRet == 1) || (fCmdRet == 2) || (fCmdRet == 0xFB) || (fCmdRet == 0x26))
            {
                if (cmdTime > CommunicationTime)
                    cmdTime = cmdTime - CommunicationTime;//减去通讯时间等于标签的实际时间
                if (cmdTime > 0)
                {
                    int tagrate = (CardNum * 1000) / cmdTime;//速度等于张数/时间
                    IntPtr ptrWnd = IntPtr.Zero;
                    ptrWnd = FindWindow(null, "UHFReader DS7 Demo V1.1");
                    if (ptrWnd != IntPtr.Zero)         // 检查当前统计窗口是否打开
                    {
                        string para = tagrate.ToString() + "," + total_tagnum.ToString() + "," + cmdTime.ToString();
                        SendMessage(ptrWnd, WM_SENDTAGSTAT, IntPtr.Zero, para);
                    }
                }

            }
            IntPtr ptrWnd1 = IntPtr.Zero;
            ptrWnd1 = FindWindow(null, "UHFReader DS7 Demo V1.1");
            if (ptrWnd1 != IntPtr.Zero)         // 检查当前统计窗口是否打开
            {
                string para = fCmdRet.ToString();
                SendMessage(ptrWnd1, WM_SENDSTATU, IntPtr.Zero, para);
            }
            ptrWnd1 = IntPtr.Zero;
        }
        #endregion

        private void inventory()
        {
            fIsInventoryScan = true;
            while (!toStopThread)
            {
                try
                {
                    if (Session == 255)
                    {
                        FastFlag = 0;
                        if (rb_mix.Checked)
                        {
                            flashmix_G2();
                        }
                        else
                        {
                            flash_G2();
                        }

                    }
                    else
                    {
                        for (int m = 0; m < AntennaNum; m++)
                        {
                            InAnt = (byte)(m | 0x80);
                            FastFlag = 1;
                            if (antlist[m] == 1)
                            {
                                if (Session > 1 && Session < 4)//s2,s3
                                {
                                    if ((check_num.Checked) && (AA_times + 1 > targettimes))
                                    {
                                        Target = Convert.ToByte(1 - Target);  //如果连续2次未读到卡片，A/B状态切换。
                                        AA_times = 0;
                                    }
                                }
                                if (rb_mix.Checked)
                                {
                                    flashmix_G2();
                                }
                                else
                                {
                                    flash_G2();
                                    PresetProfile();
                                }
                            }
                        }
                    }
                    Thread.Sleep(5);
                }
                catch (System.Exception ex)
                {
                    ex.ToString();
                }
            }

            if (ModeType == 2)
            {
                Profile = (byte)(RF_Profile | 0xC0);
                fCmdRet = RWDev.SetProfile(ref fComAdr, ref Profile, frmcomportindex);
            }

            this.Invoke((EventHandler)delegate
            {

                if (fIsInventoryScan)
                {
                    toStopThread = true;//标志，接收数据线程判断stop为true，正常情况下会自动退出线程           

                    btIventoryG2.Text = ResourceCulture.GetString("btn_inventory_start");
                    mythread.Abort();//若线程无法退出，强制结束
                    timer_answer.Enabled = false;
                    fIsInventoryScan = false;
                }
                timer_answer.Enabled = false;
                rb_mix.Enabled = true;
                rb_epc.Enabled = true;
                rb_tid.Enabled = true;
                rb_fastid.Enabled = true;
                fIsInventoryScan = false;
                btIventoryG2.Enabled = true;
                mythread = null;
            });

        }

        private void PresetProfile()
        {
            if ((readMode == 254 || readMode == 253) && (ModeType==2))//
            {
                if ((Profile == 0x01) && (readMode==253))
                {
                    if (tagrate < 150 || CardNum < 150)
                    {
                        Profile = 0xC5;
                        fCmdRet = RWDev.SetProfile(ref fComAdr, ref Profile, frmcomportindex);
                    }
                }
                else if (Profile == 0x05)
                {
                    if (NewCardNum < 5)
                    {
                        Profile = 0xCD;
                        fCmdRet = RWDev.SetProfile(ref fComAdr, ref Profile, frmcomportindex);
                        AA_times = 0;
                    }
                }
                else if (Profile == 0x0D)
                {
                    if (NewCardNum > 20)
                    {
                        Profile = 0xC5;
                        fCmdRet = RWDev.SetProfile(ref fComAdr, ref Profile, frmcomportindex);

                    }
                    else if (AA_times >= targettimes)
                    {
                        if (readMode==254)
                            Profile = 0xC5;
                        else if (readMode==253)
                            Profile = 0xC1;
                        fCmdRet = RWDev.SetProfile(ref fComAdr, ref Profile, frmcomportindex);
                        AA_times = 0;
                        Target = Convert.ToByte(1 - Target);  //如果连续2次未读到卡片，A/B状态切换。
                    }
                    
                }
            }
        }
        private void timer_answer_Tick(object sender, EventArgs e)
        {
            if (reflasg) return;
            reflasg = true;
            if (tabControl2.SelectedTab == tabPage_answer)
                updateAnswerMode();
          
            else if (tabControl2.SelectedTab == tabPage17)
            {
                updateLEDScan();
            }
            else if (tabControl2.SelectedTab == tabPage18)
            {
                updatetempquery();
            }
            else if (tabControl2.SelectedTab == tabPage19)
            {
                updatesta();
            }
            reflasg = false;
        }

        private void updateAnswerMode()
        {
            IntPtr ptrWnd = IntPtr.Zero;
            ptrWnd = FindWindow(null, "UHFReader DS7 Demo V1.1");
            if (ptrWnd != IntPtr.Zero)         // 检查当前统计窗口是否打开
            {
                string para = fCmdRet.ToString();
                SendMessage(ptrWnd, WM_SHOWNUM, IntPtr.Zero, para);
            }

            RFIDTag[] mytag = new RFIDTag[500];
            int Count = 0;
            lock (LockFlag)
            {
                lxLedControl4.Text = total_tagnum + "";
                Count = curList.Count;
                if (Count > 0)
                {
                    curList.CopyTo(mytag, 0);
                }
                curList.Clear();
            }
            for (int p = 0; p < Count; p++)
            {
                RFIDTag mtag = mytag[p];
                SendTagMessage(ptrWnd, mtag);
            }
            lxLedControl1.Text = epclist.Count + "";
            lxLedControl6.Text = tidlist.Count + "";
            ptrWnd = IntPtr.Zero;
        }

        private void updateLEDScan()
        {
            IntPtr ptrWnd = IntPtr.Zero;
            ptrWnd = FindWindow(null, "UHFReader DS7 Demo V1.1");
            if (ptrWnd != IntPtr.Zero)         // 检查当前统计窗口是否打开
            {
                string para = fCmdRet.ToString();
                SendMessage(ptrWnd, WM_SHOWNUM, IntPtr.Zero, para);
            }

            RFIDTag[] mytag = new RFIDTag[500];
            int Count = 0;
            lock (LockFlag)
            {
                lxLedControl4.Text = total_tagnum + "";
                Count = curList.Count;
                if (Count > 0)
                {
                    curList.CopyTo(mytag, 0);
                }
                curList.Clear();
            }
            for (int p = 0; p < Count; p++)
            {
                RFIDTag mtag = mytag[p];
                string str_EPC = mtag.UID;
                if (mtag.PacketParam < 128)
                {
                    int Antnum = mtag.ANT;
                    string str_ant = GetAntennaNumber(Antnum).ToString();// Convert.ToString(Antnum, 2).PadLeft(4, '0');
                    string epclen = mtag.LEN.ToString();// Convert.ToString(ce.LEN, 16);
                    string para = str_ant + "," + epclen + "," + mtag.UID + "," + mtag.RSSI.ToString() + "," + mtag.phase_begin + "," + mtag.phase_end + "," + mtag.Freqkhz;
                    SendMessage(ptrWnd, WM_LED_TAG, IntPtr.Zero, para);
                }
            }

            ptrWnd = IntPtr.Zero;
        }

        private void updatetempquery()
        {
            IntPtr ptrWnd = IntPtr.Zero;
            ptrWnd = FindWindow(null, "UHFReader DS7 Demo V1.1");
            if (ptrWnd != IntPtr.Zero)         // 检查当前统计窗口是否打开
            {
                string para = fCmdRet.ToString();
                SendMessage(ptrWnd, WM_SHOWNUM, IntPtr.Zero, para);
            }

            RFIDTag[] mytag = new RFIDTag[500];
            int Count = 0;
            lock (LockFlag)
            {
                Count = curList.Count;
                if (Count > 0)
                {
                    curList.CopyTo(mytag, 0);
                }
                curList.Clear();
            }
            for (int p = 0; p < Count; p++)
            {
                RFIDTag mtag = mytag[p];
                string str_EPC = mtag.UID;
                int Antnum = mtag.ANT;
                string str_ant = GetAntennaNumber(Antnum).ToString();// Convert.ToString(Antnum, 2).PadLeft(4, '0');
                string epclen = mtag.LEN.ToString();// Convert.ToString(ce.LEN, 16);
                string para = str_ant + "," + epclen + "," + mtag.UID + "," + mtag.RSSI.ToString() + "," + mtag.phase_begin + "," + mtag.phase_end + "," + mtag.Freqkhz;
                SendMessage(ptrWnd, WM_TEMP_TAG, IntPtr.Zero, para);
            }
            lxLedTemp.Text = epclist.Count + "";
            ptrWnd = IntPtr.Zero;
        }


        private void updatesta()
        {
            IntPtr ptrWnd = IntPtr.Zero;
            ptrWnd = FindWindow(null, "UHFReader DS7 Demo V1.1");
            if (ptrWnd != IntPtr.Zero)         // 检查当前统计窗口是否打开
            {
                string para = fCmdRet.ToString();
                SendMessage(ptrWnd, WM_SHOWNUM, IntPtr.Zero, para);
            }

            RFIDTag[] mytag = new RFIDTag[500];
            int Count = 0;
            lock (LockFlag)
            {
                Count = curList.Count;
                if (Count > 0)
                {
                    curList.CopyTo(mytag, 0);
                }
                curList.Clear();
            }
            for (int p = 0; p < Count; p++)
            {
                RFIDTag mtag = mytag[p];
                string str_EPC = mtag.UID;
                int Antnum = mtag.ANT;
                string str_ant = GetAntennaNumber(Antnum).ToString();// Convert.ToString(Antnum, 2).PadLeft(4, '0');
                string epclen = mtag.LEN.ToString();// Convert.ToString(ce.LEN, 16);
                string para = str_ant + "," + epclen + "," + mtag.UID + "," + mtag.RSSI.ToString() + "," + mtag.phase_begin + "," + mtag.phase_end + "," + mtag.Freqkhz;
                SendMessage(ptrWnd, WM_TRUTH_TAG, IntPtr.Zero, para);
            }
            lxLedTruth.Text = epclist.Count + "";
            ptrWnd = IntPtr.Zero;
        }
        
        private void radioButton_band1_CheckedChanged(object sender, EventArgs e)
        {
            int i;
            ComboBox_dmaxfre.Items.Clear();
            ComboBox_dminfre.Items.Clear();
            cmbReturnLossFreq.Items.Clear();
            for (i = 0; i < 20; i++)
            {
                ComboBox_dminfre.Items.Add(Convert.ToString(920.125 + i * 0.25) + " MHz");
                ComboBox_dmaxfre.Items.Add(Convert.ToString(920.125 + i * 0.25) + " MHz");
                cmbReturnLossFreq.Items.Add(Convert.ToString(920.125 + i * 0.25));
            }
            ComboBox_dmaxfre.SelectedIndex = 19;
            ComboBox_dminfre.SelectedIndex = 0;
            cmbReturnLossFreq.SelectedIndex = 10;
        }



        private void radioButton_band2_CheckedChanged(object sender, EventArgs e)
        {
            int i;
            ComboBox_dmaxfre.Items.Clear();
            ComboBox_dminfre.Items.Clear();
            cmbReturnLossFreq.Items.Clear();
            for (i = 0; i < 50; i++)
            {
                ComboBox_dminfre.Items.Add(Convert.ToString(902.75 + i * 0.5) + " MHz");
                ComboBox_dmaxfre.Items.Add(Convert.ToString(902.75 + i * 0.5) + " MHz");
                cmbReturnLossFreq.Items.Add(Convert.ToString(902.75 + i * 0.5));
            }
            ComboBox_dmaxfre.SelectedIndex = 49;
            ComboBox_dminfre.SelectedIndex = 0;
            cmbReturnLossFreq.SelectedIndex = 25;
        }

        private void radioButton_band3_CheckedChanged(object sender, EventArgs e)
        {
            int i;
            ComboBox_dmaxfre.Items.Clear();
            ComboBox_dminfre.Items.Clear();
            cmbReturnLossFreq.Items.Clear();
            for (i = 0; i < 32; i++)
            {
                ComboBox_dminfre.Items.Add(Convert.ToString(917.1 + i * 0.2) + " MHz");
                ComboBox_dmaxfre.Items.Add(Convert.ToString(917.1 + i * 0.2) + " MHz");
                cmbReturnLossFreq.Items.Add(Convert.ToString(917.1 + i * 0.2));
            }
            ComboBox_dmaxfre.SelectedIndex = 31;
            ComboBox_dminfre.SelectedIndex = 0;
            cmbReturnLossFreq.SelectedIndex = 16;
        }

        private void radioButton_band4_CheckedChanged(object sender, EventArgs e)
        {
            int i;
            ComboBox_dminfre.Items.Clear();
            ComboBox_dmaxfre.Items.Clear();
            cmbReturnLossFreq.Items.Clear();
            for (i = 0; i < 15; i++)
            {
                ComboBox_dminfre.Items.Add(Convert.ToString(865.1 + i * 0.2) + " MHz");
                ComboBox_dmaxfre.Items.Add(Convert.ToString(865.1 + i * 0.2) + " MHz");
                cmbReturnLossFreq.Items.Add(Convert.ToString(865.1 + i * 0.2));
            }
            ComboBox_dmaxfre.SelectedIndex = 14;
            ComboBox_dminfre.SelectedIndex = 0;
            cmbReturnLossFreq.SelectedIndex = 7;
        }

        private void CheckBox_SameFre_CheckedChanged(object sender, EventArgs e)
        {
            if (CheckBox_SameFre.Checked)
                ComboBox_dmaxfre.SelectedIndex = ComboBox_dminfre.SelectedIndex;
        }

        private void btworkmode_Click(object sender, EventArgs e)
        {
            byte Read_mode = 0;
            Read_mode = Convert.ToByte(comboBox_mode.SelectedIndex);
            fCmdRet = RWDev.SetWorkMode(ref fComAdr, Read_mode, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_mode_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_mode_set_succeed") + comboBox_mode.Text;
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btResponse_Click(object sender, EventArgs e)
        {
            byte RepCondition = 0;
            byte RepPauseTime = 0;
            RepPauseTime = Convert.ToByte(comboBox_RespTime.SelectedIndex);
            fCmdRet = RWDev.SetResponsePamametersofAuto_runningMode(ref fComAdr, RepCondition, RepPauseTime, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_response_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_response_set_succeed") + comboBox_Resp.Text;
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btGetWorkmodepara_Click(object sender, EventArgs e)
        {
            try {
                byte Read_mode = 0;
                byte Accuracy = 0;
                byte RepCondition = 0;
                byte RepPauseTime = 0;
                byte ReadPauseTim = 0;
                byte TagProtocol = 0;
                byte MaskMem = 0;
                byte[] MaskAdr = new byte[2];
                byte[] MaskData = new byte[100];
                byte MaskLen = 0;
                byte TriggerTime = 0;
                byte AdrTID = 0;
                byte LenTID = 0;
                int i, m_byte;
                string temp;
                temp = "";
                text_madds.Text = "";
                text_mlen.Text = "";
                text_mdata.Text = "";
                text_tidaddr.Text = "";
                text_tidlen.Text = "";
                fCmdRet = RWDev.GetSystemParameter(ref fComAdr, ref Read_mode, ref Accuracy, ref RepCondition, ref RepPauseTime, ref ReadPauseTim, ref TagProtocol, ref MaskMem, MaskAdr, ref MaskLen, MaskData, ref TriggerTime, ref AdrTID, ref LenTID, frmcomportindex);
                if (fCmdRet != 0)
                {
                    string strLog = ResourceCulture.GetString("log_mode_get_failed") + GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
                else
                {
                    comboBox_mode.SelectedIndex = Convert.ToInt32(Read_mode);

                    //comboBox_Resp.SelectedIndex = RepCondition;
                    comboBox_RespTime.SelectedIndex = RepPauseTime;
                    if (comboBox_Resp.SelectedIndex == 1)
                        comboBox_RespTime.Enabled = true;
                    else
                        comboBox_RespTime.Enabled = false;
                    comboBox_intervalT.SelectedIndex = Convert.ToInt32(ReadPauseTim);
                    switch (TagProtocol)
                    {
                        case 0:
                            rb_mulEPC.Checked = true;
                            break;
                        case 1:
                            rb_mulTID.Checked = true;
                            break;
                        case 2:
                            rb_Reserve.Checked = true;
                            break;
                        case 3:
                            rb_g2epc.Checked = true;
                            break;
                        case 4:
                            rb_g2tid.Checked = true;
                            break;
                        case 5:
                            rb_g2user.Checked = true;
                            break;
                    }
                    switch (MaskMem)
                    {
                        case 1:
                            rb_MaskEPC.Checked = true;
                            break;
                        case 2:
                            rb_MaskTID.Checked = true;
                            break;
                        case 3:
                            rb_MaskUser.Checked = true;
                            break;
                    }
                    for (i = 0; i < 2; i++)
                        temp = temp + Convert.ToString(MaskAdr[i], 16).PadLeft(2, '0');
                    text_madds.Text = temp;
                    text_mlen.Text = Convert.ToString(MaskLen, 16).PadLeft(2, '0');
                    temp = "";
                    if ((MaskLen % 8) == 0)
                        m_byte = MaskLen / 8;
                    else
                        m_byte = MaskLen / 8 + 1;
                    for (i = 0; i < m_byte; i++)
                        temp = temp + Convert.ToString(MaskData[i], 16).PadLeft(2, '0');
                    text_mdata.Text = temp;
                    comboBox_trigger.SelectedIndex = TriggerTime;
                    text_tidaddr.Text = AdrTID + "";
                    text_tidlen.Text = LenTID + "";
                    string strLog = ResourceCulture.GetString("log_mode_get_succeed");
                    WriteLog(lrtxtLog, strLog, 0);
                }
            } catch (Exception ex)
            { ex.ToString(); }
        }

        private void comboBox_Resp_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox_Resp.SelectedIndex == 1)
                comboBox_RespTime.Enabled = true;
            else
                comboBox_RespTime.Enabled = false;
        }

        private void btGetActivedata_Click(object sender, EventArgs e)
        {

        }
        

         

        private void Maintab_SelectedIndexChanged(object sender, EventArgs e)
        {
          
            if (fIsInventoryScan)
            {
                toStopThread = true;
                btIventoryG2.Enabled = false;
                btIventoryG2.BackColor = Color.Transparent;
                btIventoryG2.Text = ResourceCulture.GetString("btn_inventory_start");
            }

            timer_runmode.Enabled = false;
            timer_answer.Enabled = false;
            timer_EAS.Enabled = false;
            Timer_Test_6B.Enabled = false;
            timer_Buff.Enabled = false;
            timer_RealTime.Enabled = false;
            btIventoryG2.Text = ResourceCulture.GetString("btn_inventory_start");
            btCheckEASAlarm.Text = ResourceCulture.GetString("btn_eas_alarm");
            btStartMactive.Text = ResourceCulture.GetString("btn_inventory_start");
            pictureBox2.Visible = false;
            btIventoryG2.BackColor = Color.Transparent;
            btStartMactive.BackColor = Color.Transparent;
            btCheckEASAlarm.BackColor = Color.Transparent;
            btInventory6B.Text = ResourceCulture.GetString("btn_inventory_start");
            btInventory6B.BackColor = Color.Transparent;


            if (comboBox_EPC.Text == "" && comboBox_EPC.Items.Count > 0)
            {
                comboBox_EPC.SelectedIndex = 0;
            }
            if ((ReadTypes == "16") || (ReadTypes == "21"))
            {
                group_ant1.Enabled = false;
                check_ant1.Checked = true;
            }
            else
            {
                if (com_S.SelectedIndex != 4)
                    group_ant1.Enabled = true;
                else
                    group_ant1.Enabled = false;
            }

            
        }


        private void btClearBuffer_Click(object sender, EventArgs e)
        {
            fCmdRet = RWDev.ClearTagBuffer(ref fComAdr, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_clear_buffer_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_clear_buffer_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void tb_Port_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = ("0123456789".IndexOf(Char.ToUpper(e.KeyChar)) < 0);
        }

        private void text_address_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = ("0123456789ABCDEF".IndexOf(Char.ToUpper(e.KeyChar)) < 0);
        }

        int AntennaNum = 1;
        int ModeType = 2;
        private void btGetInformation_Click(object sender, EventArgs e)
        {
            byte TrType = 0;
            byte[] VersionInfo = new byte[2];
            byte ReaderType = 0;
            byte mReaderType = 0;
            byte ScanTime = 0;
            byte dmaxfre = 0;
            byte dminfre = 0;
            byte powerdBm = 0;
            byte FreBand = 0;
            byte AntCfg0 = 0;
            byte BeepEn = 0;
            byte AntCfg1 = 0;
            byte OutputRep = 0;
            byte CheckAnt = 0;
            text_RDVersion.Text = "";
            int ctime = System.Environment.TickCount;
            rb_epc.Checked = false;
            fCmdRet = RWDev.GetReaderInformation(ref fComAdr, VersionInfo, ref mReaderType, ref TrType, ref dmaxfre, ref dminfre, ref powerdBm, ref ScanTime, ref AntCfg0, ref BeepEn, ref AntCfg1, ref CheckAnt, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_reader_info_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                CommunicationTime = System.Environment.TickCount - ctime;
                byte Profile = 0;
                fCmdRet = RWDev.SetProfile(ref fComAdr, ref Profile, frmcomportindex);
                if (fCmdRet == 0)
                {
                    RF_Profile = Profile;
                }

                if (mReaderType == 0x82 || mReaderType == 0x83)
                {
                    string ReaderName = "";
                    if (mReaderType == 0x82)
                    {
                        ReaderName = "UHF7001";
                        AntennaNum = 1;
                    }
                    if (mReaderType == 0x83)
                    {
                        ReaderName = "UHF7002";
                        AntennaNum = 2;
                    }
                    text_RDVersion.Text = ReaderName + "-V" + Convert.ToString(VersionInfo[0], 10).PadLeft(2, '0') + "." + Convert.ToString(VersionInfo[1], 10).PadLeft(2, '0');
                    fCmdRet = RWDev.GetModuleDetails(ref fComAdr, VersionInfo, ref ReaderType, ref TrType, frmcomportindex);
                    if (fCmdRet == 0)
                    {
                        text_RDVersion.Text += ("-" + Convert.ToString(VersionInfo[0], 10).PadLeft(2, '0') + "." + Convert.ToString(VersionInfo[1], 10).PadLeft(2, '0')
                            + "(" + Convert.ToString(ReaderType, 16).PadLeft(2, '0') + ")");
                    }
                }
                else
                {
                    text_RDVersion.Text = Convert.ToString(VersionInfo[0], 10).PadLeft(2, '0') 
                                        + "." + Convert.ToString(VersionInfo[1], 10).PadLeft(2, '0')
                                        + "(" + Convert.ToString(mReaderType, 16).PadLeft(2, '0')
                                        +")";
                }
                comboBox_maxtime.SelectedIndex = ScanTime;
                
                if (ReaderType == 0x62 || ReaderType == 0x61 || ReaderType == 0x64
                    || ReaderType == 0x66 || ReaderType == 0x65 || ReaderType == 0x67 || ReaderType == 0x68)
                {
                    ModeType = 0;
                    comboBox4.Items.Clear();
                    comboBox4.Items.Add("Profile 0:Tari 12.5us，FM0 160KHz");
                    comboBox4.Items.Add("Profile 1:Tari 12.5us，Miller 8 160KHz");
                    comboBox4.Items.Add("Profile 2:Tari 12.5us，FM0 250KHz");
                    comboBox4.Items.Add("Profile 3:Tari 6.25us，Miller 4 320KHz");
                    comboBox4.Items.Add("Profile 4:Tari 12.5us，Miller 4 160KHz");
                    comboBox4.SelectedIndex = 4;

                }
                else if (ReaderType == 0x11)
                {
                    ModeType = 3;
                }
                else if (ReaderType == 0x91 || ReaderType == 0x92 || ReaderType == 0x93 || ReaderType == 0x94)//FD
                {
                    comboBox4.Items.Clear();
                    comboBox4.Items.Add("Profile 20: 80kHZ,FM0    ,Tari 25 us");
                    comboBox4.Items.Add("Profile 21:250kHZ,Miller4,Tari 25 us");
                    comboBox4.Items.Add("Profile 22:300kHZ,Miller4,Tari 25 us");
                    comboBox4.Items.Add("Profile 23:400kHZ,FM0    ,Tari 6.25us");
                    comboBox4.Items.Add("Profile 24:300kHZ,Miller2,Tari 25 us");
                    comboBox4.Items.Add("Profile 25:300kHZ,Miller8,Tari 25 us");
                    comboBox4.Items.Add("Profile 26: 80kHZ,Miller4,Tari 25 us");
                    comboBox4.Items.Add("Profile 27:160kHZ,Miller4,Tari 25 us");
                    comboBox4.Items.Add("Profile 28:400kHZ,Miller2,Tari 6.25us");
                    comboBox4.SelectedIndex = 1;
                    ModeType = 4;
                }
                else if(ReaderType==0x0B || ReaderType == 0x0C || ReaderType == 0x12 || ReaderType == 0x16
                    || ReaderType == 0x1A || ReaderType == 0x12 || ReaderType == 0x20 || ReaderType == 0x21
                    || ReaderType == 0x23 || ReaderType == 0x26 || ReaderType == 0x27 || ReaderType == 0x28
                    || ReaderType == 0x36 || ReaderType == 0x37 || ReaderType == 0x8A || ReaderType == 0x8B
                    || ReaderType == 0x8C || ReaderType == 0x8D)//R2000
                {
                    ModeType = 1;
                    comboBox4.Items.Clear();
                    comboBox4.Items.Add("Profile 0:Tari 25uS，FM0 40KHz");
                    comboBox4.Items.Add("Profile 1:Tari 25uS，Miller 4 250KHz");
                    comboBox4.Items.Add("Profile 2:Tari 25uS，Miller 4 300KHz");
                    comboBox4.Items.Add("Profile 3:Tari 6.25uS，FM0 400KHz");
                    comboBox4.SelectedIndex = 1;
                }
                //else if (ReaderType == 0x71 || ReaderType == 0x31 || ReaderType == 0x70//RRUx180
                //    || ReaderType == 0x72 || ReaderType == 0x5F || ReaderType == 0x7F
                //    || ReaderType == 0x76 || ReaderType == 0x56 || ReaderType == 0x38//RRUx189
                //    || ReaderType == 0x57 || ReaderType == 0x77 || ReaderType == 0x39//RRUx199
                //    || ReaderType == 0x55 || ReaderType == 0x75 || ReaderType == 0x35 //RRUx182
                //    || ReaderType == 0x33 || ReaderType == 0x53 || ReaderType == 0x73
                //    || ReaderType == 0x3A || ReaderType == 0x5A || ReaderType == 0x7A
                //    || ReaderType == 0x3B || ReaderType == 0x5B || ReaderType == 0x7B//RRUx181
                //    || ReaderType == 0x3C || ReaderType == 0x5C || ReaderType == 0x7C
                //    || ReaderType == 0x3D || ReaderType == 0x5D || ReaderType == 0x7D//RRUx181
                //    || ReaderType == 0x3E || ReaderType == 0x5E || ReaderType == 0x7E
                //    || ReaderType == 0x40 || ReaderType == 0x41 || ReaderType == 0x42
                //    || ReaderType == 0x6A || ReaderType == 0x6B || ReaderType == 0x6C
                //    || ReaderType == 0x6D || ReaderType == 0x6E || ReaderType == 0x6F)
                else
                {
                    ModeType = 2;

                    comboBox4.Items.Clear();
                    comboBox4.Items.Add("Profile 11:640kHZ,FM0    ,Tari 7.5 us,PIE 2");
                    comboBox4.Items.Add("Profile  1:640kHZ,Miller2,Tari 7.5 us,PIE 2");
                    comboBox4.Items.Add("Profile 15:640kHZ,Miller4,Tari 7.5 us,PIE 2");
                    comboBox4.Items.Add("Profile 12:320kHZ,Miller2,Tari 15  us,PIE 2");
                    comboBox4.Items.Add("Profile  3:320kHZ,Miller2,Tari 20  us,PIE 2");
                    comboBox4.Items.Add("Profile  5:320kHZ,Miller4,Tari 20  us,PIE 2");
                    comboBox4.Items.Add("Profile  7:250kHZ,Miller4,Tari 20  us,PIE 2");
                    comboBox4.Items.Add("Profile 13:160kHZ,Miller8,Tari 20  us,PIE 2");
                    comboBox4.Items.Add("Profile 50:640kHZ,FM0    ,Tari 6.25us,PIE 1.5");
                    comboBox4.Items.Add("Profile 51:640kHZ,Miller2,Tari 6.25us,PIE 1.5");
                    comboBox4.Items.Add("Profile 52:426kHZ,FM0    ,Tari 15  us,PIE 1.5");
                    comboBox4.Items.Add("Profile 53:640kHZ,Miller4,Tari 7.5 us,PIE 1.5");
                    comboBox4.SelectedIndex = 5;
                }
                rb_epc.Checked = true;
               
                ShowAntenna(AntennaNum);
                if (powerdBm < 34)
                    ComboBox_PowerDbm.SelectedIndex = Convert.ToInt32(powerdBm);
                else
                {
                    btGetRfPower_Click(null, null);
                }
                text_address.Text = Convert.ToString(fComAdr, 16).PadLeft(2, '0');
                if ((dmaxfre == 255) && (dminfre == 255))
                {
                    button11_Click(null, null);
                }
                else
                {
                    FreBand = Convert.ToByte(((dmaxfre & 0xc0) >> 4) | (dminfre >> 6));
                    switch (FreBand)
                    {
                        case 1:
                            {
                                radioButton_band1.Checked = true;
                                fdminfre = 920.125 + (dminfre & 0x3F) * 0.25;
                                fdmaxfre = 920.125 + (dmaxfre & 0x3F) * 0.25;
                            }
                            break;
                        case 2:
                            {
                                radioButton_band2.Checked = true;
                                fdminfre = 902.75 + (dminfre & 0x3F) * 0.5;
                                fdmaxfre = 902.75 + (dmaxfre & 0x3F) * 0.5;
                            }
                            break;
                        case 3:
                            {
                                radioButton_band3.Checked = true;
                                fdminfre = 917.1 + (dminfre & 0x3F) * 0.2;
                                fdmaxfre = 917.1 + (dmaxfre & 0x3F) * 0.2;
                            }
                            break;
                        case 4:
                            {
                                radioButton_band4.Checked = true;
                                fdminfre = 865.1 + (dminfre & 0x3F) * 0.2;
                                fdmaxfre = 865.1 + (dmaxfre & 0x3F) * 0.2;
                            }
                            break;
                        case 8:
                            {
                                radioButton_band8.Checked = true;
                                fdminfre = 840.125 + (dminfre & 0x3F) * 0.25;
                                fdmaxfre = 840.125 + (dmaxfre & 0x3F) * 0.25;
                            }
                            break;
                        case 12:
                            {
                                radioButton_band12.Checked = true;
                                fdminfre = 902 + (dminfre & 0x3F) * 0.5;
                                fdmaxfre = 902 + (dmaxfre & 0x3F) * 0.5;
                            }
                            break;
                        case 0:
                            {
                                radioButton_band0.Checked = true;
                                fdminfre = 840 + (dminfre & 0x3F) * 2;
                                fdmaxfre = 840 + (dmaxfre & 0x3F) * 2;
                            }
                            break;
                    }
                    if (fdmaxfre != fdminfre)
                        CheckBox_SameFre.Checked = false;
                    ComboBox_dminfre.SelectedIndex = dminfre & 0x3F;
                    ComboBox_dmaxfre.SelectedIndex = dmaxfre & 0x3F;
                }
                switch (BeepEn)
                {
                    case 1:
                        Radio_beepEn.Checked = true;
                        break;
                    case 0:
                        Radio_beepDis.Checked = true;
                        break;
                }

                if ((AntCfg0 & 0x01) == 0x01)
                {
                    check_ant1.Checked = true;
                    checkant1.Checked = true;
                    led_ant1.Checked = true;
                }
                else
                {
                    check_ant1.Checked = false;
                    checkant1.Checked = false;
                    led_ant1.Checked = false;
                }

                if ((AntCfg0 & 0x02) == 0x02)
                {
                    check_ant2.Checked = true;
                    checkant2.Checked = true;
                    led_ant2.Checked = true;
                }
                else
                {
                    check_ant2.Checked = false;
                    checkant2.Checked = false;
                    led_ant2.Checked = false;
                }



                if ((OutputRep & 0x01) == 1)
                    check_OutputRep1.Checked = true;
                else
                    check_OutputRep1.Checked = false;

                if ((OutputRep & 0x02) == 2)
                    check_OutputRep2.Checked = true;
                else
                    check_OutputRep2.Checked = false;

                if ((OutputRep & 0x04) == 4)
                    check_OutputRep3.Checked = true;
                else
                    check_OutputRep3.Checked = false;

                if ((OutputRep & 0x08) == 8)
                    check_OutputRep4.Checked = true;
                else
                    check_OutputRep4.Checked = false;

                if (CheckAnt == 0)
                {
                    rb_Closecheckant.Checked = true;
                }
                else
                {
                    rb_Opencheckant.Checked = true;
                }
                string strLog = ResourceCulture.GetString("log_get_reader_info_succeed");
                WriteLog(lrtxtLog, strLog, 0);


            }
        }

        private void ShowAntenna(int antennanum)
        {
            ////////////
            cbbAnt.Items.Clear();
            //cbb_led_antenna.Items.Clear();
            comboBox2.Items.Clear();
            comboBox12.Items.Clear();
            for (int m = 0; m < antennanum; m++)
            {
                cbbAnt.Items.Add(ResourceCulture.GetString("cbb_item_antenna") + Convert.ToString(m + 1));
                comboBox2.Items.Add(ResourceCulture.GetString("cbb_item_antenna") + Convert.ToString(m + 1));
                comboBox12.Items.Add(ResourceCulture.GetString("cbb_item_antenna") + Convert.ToString(m + 1));
            }
            //cbb_led_antenna.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            comboBox12.SelectedIndex = 0;
            checkant1.Visible = false;
            checkant2.Visible = false;
           

            check_ant1.Visible = false;
            check_ant2.Visible = false;
            
            
            led_ant1.Visible = false;
            led_ant2.Visible = false;

            txtPower1.Enabled = false;
            txtPower2.Enabled = false;
           
            switch (antennanum)
            {
                case 1:
                    checkant1.Visible = true;
                    check_ant1.Visible = true;
                    txtPower1.Enabled = true;
                    led_ant1.Visible = true;
                    break;
                case 2:
                    checkant1.Visible = true;
                    checkant2.Visible = true;
                    check_ant1.Visible = true;
                    check_ant2.Visible = true;              
                    txtPower1.Enabled = true;
                    txtPower2.Enabled = true;
                    led_ant1.Visible = true;
                    led_ant2.Visible = true;
                    break;
            }
        }
        private void btDefault_Click(object sender, EventArgs e)
        {
            byte aNewComAdr, powerDbm, dminfre, dmaxfre, scantime;
            dminfre = 128;
            dmaxfre = 49;
            aNewComAdr = 0x00;
            powerDbm = 30;
            if (ModeType == 0)
                powerDbm = 33;
            else if (ModeType == 1)
                powerDbm = 30;
            fBaud = 5;
            scantime = 0;
            ComboBox_baud.SelectedIndex = 3;
            fCmdRet = RWDev.SetAddress(ref fComAdr, aNewComAdr, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_address_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_address_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }

            fCmdRet = RWDev.SetRfPower(ref fComAdr, powerDbm, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_power_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_power_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }

            fCmdRet = RWDev.SetRegion(ref fComAdr, dmaxfre, dminfre, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_freq_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_freq_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }

            fCmdRet = RWDev.SetBaudRate(ref fComAdr, fBaud, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_baudrate_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_baudrate_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }

            fCmdRet = RWDev.SetInventoryScanTime(ref fComAdr, scantime, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_inventory_scan_time_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_inventory_scan_time_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
            btGetInformation_Click(null,null);
        }

        private void btaddress_Click(object sender, EventArgs e)
        {
            byte aNewComAdr = Convert.ToByte(text_address.Text, 16);
            fCmdRet = RWDev.SetAddress(ref fComAdr, aNewComAdr, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_address_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_address_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btFreq_Click(object sender, EventArgs e)
        {
            byte dminfre, dmaxfre;
            int band = 2;
            if (radioButton_band1.Checked)
                band = 1;
            if (radioButton_band2.Checked)
                band = 2;
            if (radioButton_band3.Checked)
                band = 3;
            if (radioButton_band4.Checked)
                band = 4;
            if (radioButton_band8.Checked)
                band = 8;
            if (radioButton_band12.Checked)
                band = 12;
            if (radioButton_band0.Checked)
                band = 0;
            dminfre = Convert.ToByte(((band & 3) << 6) | (ComboBox_dminfre.SelectedIndex & 0x3F));
            dmaxfre = Convert.ToByte(((band & 0x0c) << 4) | (ComboBox_dmaxfre.SelectedIndex & 0x3F));
            fCmdRet = RWDev.SetRegion(ref fComAdr, dmaxfre, dminfre, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_freq_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_freq_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void BT_DBM_Click(object sender, EventArgs e)
        {
            byte powerDbm = (byte)ComboBox_PowerDbm.SelectedIndex;
            fCmdRet = RWDev.SetRfPower(ref fComAdr, powerDbm, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_power_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_power_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btBaudRate_Click(object sender, EventArgs e)
        {
            byte fBaud = (byte)ComboBox_baud.SelectedIndex;
            if (fBaud > 2)
                fBaud = (byte)(fBaud + 2);
            fCmdRet = RWDev.SetBaudRate(ref fComAdr, fBaud, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_baudrate_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_baudrate_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btSerial_Click(object sender, EventArgs e)
        {
            byte[] SeriaNo = new byte[4];
            text_Serial.Text = "";
            fCmdRet = RWDev.GetSeriaNo(ref fComAdr, SeriaNo, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_reader_no_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                text_Serial.Text = ByteArrayToHexString(SeriaNo);
                string strLog = ResourceCulture.GetString("log_get_reader_no_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btMDVersion_Click(object sender, EventArgs e)
        {
            byte[] Version = new byte[2];
            text_MDVersion.Text = "";
            fCmdRet = RWDev.GetModuleVersion(ref fComAdr, Version, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_module_version_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                text_MDVersion.Text = Convert.ToString(Version[0], 10).PadLeft(2, '0') + "." + Convert.ToString(Version[1], 10).PadLeft(2, '0');
                string strLog = ResourceCulture.GetString("log_get_module_version_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void Button_Beep_Click(object sender, EventArgs e)
        {
            byte BeepEn = 0;
            if (Radio_beepEn.Checked)
                BeepEn = 1;
            else
                BeepEn = 0;
            fCmdRet = RWDev.SetBeepNotification(ref fComAdr, BeepEn, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_beep_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_beep_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btRelay_Click(object sender, EventArgs e)
        {
            byte RelayTime = 0;
            byte relayNum = (byte)comboBox19.SelectedIndex;
            byte relayAction = (byte)cbb_relayAction.SelectedIndex;
            RelayTime = Convert.ToByte(ComboBox_RelayTime.SelectedIndex + 1);
            fCmdRet = RWDev.RelaysControll(ref fComAdr, relayNum, relayAction, RelayTime, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_relay_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_relay_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btOutputRep_Click(object sender, EventArgs e)
        {
            byte OutputRep = 0;
            if (check_OutputRep1.Checked)
                OutputRep = Convert.ToByte(OutputRep | 0x01);
            if (check_OutputRep2.Checked)
                OutputRep = Convert.ToByte(OutputRep | 0x02);
            if (check_OutputRep3.Checked)
                OutputRep = Convert.ToByte(OutputRep | 0x04);
            if (check_OutputRep3.Checked)
                OutputRep = Convert.ToByte(OutputRep | 0x08);
            fCmdRet = RWDev.SetNotificationPulseOutput(ref fComAdr, OutputRep, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_notification_output_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_notification_output_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void Button_SetGPIO_Click(object sender, EventArgs e)
        {
            byte OutputPin = 0;
            if (check_out1.Checked)
                OutputPin = Convert.ToByte(OutputPin | 0x01);
            if (check_out2.Checked)
                OutputPin = Convert.ToByte(OutputPin | 0x02);
            if (check_out3.Checked)
                OutputPin = Convert.ToByte(OutputPin | 0x04);
            if (check_out4.Checked)
                OutputPin = Convert.ToByte(OutputPin | 0x08);
            fCmdRet = RWDev.SetGPIO(ref fComAdr, OutputPin, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_GPIO_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_GPIO_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void Button_GetGPIO_Click(object sender, EventArgs e)
        {
            byte OutputPin = 0;
            fCmdRet = RWDev.GetGPIOStatus(ref fComAdr, ref OutputPin, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_GPIO_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                if ((OutputPin & 0x10) == 0x10)
                    check_out1.Checked = true;
                else
                    check_out1.Checked = false;

                if ((OutputPin & 0x20) == 0x20)
                    check_out2.Checked = true;
                else
                    check_out2.Checked = false;

                if ((OutputPin & 0x40) == 0x40)
                    check_out3.Checked = true;
                else
                    check_out3.Checked = false;

                if ((OutputPin & 0x80) == 0x80)
                    check_out4.Checked = true;
                else
                    check_out4.Checked = false;

                if ((OutputPin & 0x01) == 1)
                    check_int1.Checked = true;
                else
                    check_int1.Checked = false;

                if ((OutputPin & 0x02) == 2)
                    check_int2.Checked = true;
                else
                    check_int2.Checked = false;

                if ((OutputPin & 0x04) == 4)
                    check_int3.Checked = true;
                else
                    check_int3.Checked = false;

                if ((OutputPin & 0x08) == 8)
                    check_int4.Checked = true;
                else
                    check_int4.Checked = false;
                string strLog = ResourceCulture.GetString("log_get_GPIO_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btSetcheckant_Click(object sender, EventArgs e)
        {
            byte CheckAnt = 0;
            if (rb_Opencheckant.Checked)
                CheckAnt = 1;
            else
                CheckAnt = 0;
            fCmdRet = RWDev.SetCheckAnt(ref fComAdr, CheckAnt, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_check_ant_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_check_ant_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void Button_Ant_Click(object sender, EventArgs e)
        {
            byte ANT = 0;
            byte SetOnce = 0;
            if (checkant1.Checked) ANT = Convert.ToByte(ANT | 0x01);
            if (checkant2.Checked) ANT = Convert.ToByte(ANT | 0x02);
            if (!checkBox2.Checked) SetOnce = 0x80;
            fCmdRet = RWDev.SetAntennaMultiplexing(ref fComAdr, (byte)(ANT | SetOnce), frmcomportindex);

            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_ant_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {

                string strLog = ResourceCulture.GetString("log_set_ant_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }


        private void btAccuracy_Click(object sender, EventArgs e)
        {
           
        }

        private void btMaskSet_Click(object sender, EventArgs e)
        {
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            if ((text_madds.Text.Length != 4) || (text_mlen.Text.Length != 2) || (text_mdata.Text.Length % 2 != 0))
            {
                MessageBox.Show(ResourceCulture.GetString("hint_input_correctly"), ResourceCulture.GetString("hint_info"));
                return;
            }
            if (rb_MaskEPC.Checked) MaskMem = 1;
            if (rb_MaskTID.Checked) MaskMem = 2;
            if (rb_MaskUser.Checked) MaskMem = 3;
            MaskAdr = HexStringToByteArray(text_madds.Text.Trim());
            MaskLen = Convert.ToByte(text_mlen.Text, 16);
            MaskData = HexStringToByteArray(text_mdata.Text.Trim());
            fCmdRet = RWDev.SetMask(ref fComAdr, MaskMem, MaskAdr, MaskLen, MaskData, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_mask_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_mask_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void bt_typeTag_Click(object sender, EventArgs e)
        {
            byte Protocol = 0;
            if (rb_mulEPC.Checked) Protocol = 0;
            if (rb_mulTID.Checked) Protocol = 1;
            if (rb_Reserve.Checked) Protocol = 2;
            if (rb_g2epc.Checked) Protocol = 3;
            if (rb_g2tid.Checked) Protocol = 4;
            if (rb_g2user.Checked) Protocol = 5;
            fCmdRet = RWDev.SelectTagType(ref fComAdr, Protocol, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_type_setting_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_type_setting_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void bttrigger_Click(object sender, EventArgs e)
        {
            byte TriggerTime = 0;
            TriggerTime = Convert.ToByte(comboBox_trigger.SelectedIndex);
            fCmdRet = RWDev.SetTriggerTime(ref fComAdr, TriggerTime, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_trigger_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_trigger_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btTIDpara_Click(object sender, EventArgs e)
        {
            byte LenTID = 0;
            byte AdrTID = 0;
            if ((text_tidaddr.Text.Length ==0) || (text_tidlen.Text.Length ==0))
            {
                MessageBox.Show(ResourceCulture.GetString("hint_tid_error"), ResourceCulture.GetString("hint_info"));
                return;
            }
            AdrTID = Convert.ToByte(text_tidaddr.Text, 10);
            LenTID = Convert.ToByte(text_tidlen.Text, 10);
            fCmdRet = RWDev.SetTIDParameter(ref fComAdr, AdrTID, LenTID, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_TID_setting_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_TID_setting_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btSetQS_Click(object sender, EventArgs e)
        {
            byte QValue, Session;
            QValue = Convert.ToByte(com_acQ.SelectedIndex);
            Session = Convert.ToByte(com_acS.SelectedIndex);
            fCmdRet = RWDev.SetQS(ref fComAdr, QValue, Session, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_multiple_tag_setting_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_multiple_tag_setting_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btGetQS_Click(object sender, EventArgs e)
        {
            byte QValue, Session;
            QValue = 0;
            Session = 0;
            fCmdRet = RWDev.GetQS(ref fComAdr, ref QValue, ref Session, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_multiple_tag_setting_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                com_acQ.SelectedIndex = QValue;
                com_acS.SelectedIndex = Session;
                string strLog = ResourceCulture.GetString("log_get_multiple_tag_setting_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btInterval_Click(object sender, EventArgs e)
        {
            byte ReadPauseTim = 0;
            ReadPauseTim = Convert.ToByte(comboBox_intervalT.SelectedIndex);
            fCmdRet = RWDev.SetInventoryInterval(ref fComAdr, ReadPauseTim, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_interval_time_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_interval_time_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btSelectTag_Click(object sender, EventArgs e)
        {
            text_epc.Text = comboBox_EPC.Text;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                maskadr_textbox.Enabled = true;
                maskLen_textBox.Enabled = true;
                maskData_textBox.Enabled = true;
                R_EPC.Enabled = true;
                R_TID.Enabled = true;
                R_User.Enabled = true;
            }
            else
            {
                maskadr_textbox.Enabled = false;
                maskLen_textBox.Enabled = false;
                maskData_textBox.Enabled = false;
                R_EPC.Enabled = false;
                R_TID.Enabled = false;
                R_User.Enabled = false;
            }
        }
        //E200 F351 4818 3C90 07C2 5000 10BC 9D00
        private void btRead_Click(object sender, EventArgs e)
        {
            byte WordPtr, ENum;
            byte Num = 0;
            byte Mem = 0;
            string str = ""; ;
            byte[] CardData = new byte[320];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            text_WriteData.Text = "";
            if (checkBox1.Checked)
            {
                if ((maskadr_textbox.Text == "") || (maskLen_textBox.Text == "") || (maskData_textBox.Text == ""))
                {
                    return;
                }
                ENum = 255;
                if (R_EPC.Checked) MaskMem = 1;
                if (R_TID.Checked) MaskMem = 2;
                if (R_User.Checked) MaskMem = 3;
                MaskAdr = HexStringToByteArray(maskadr_textbox.Text);
                MaskLen = Convert.ToByte(maskLen_textBox.Text, 16);
                MaskData = HexStringToByteArray(maskData_textBox.Text);
            }
            else
            {
                if (check_selecttag.Checked)
                    str = text_epc.Text;
                else
                    str = "";
                ENum = Convert.ToByte(str.Length / 4);
            }
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            if (C_Reserve.Checked)
                Mem = 0;
            if (C_EPC.Checked)
                Mem = 1;
            if (C_TID.Checked)
                Mem = 2;
            if (C_User.Checked)
                Mem = 3;
            if (text_WordPtr.Text == "" || text_RWlen.Text == "" || text_AccessCode2.Text.Length != 8)
            {
                return;
            }
            WordPtr = (byte)Convert.ToInt32(text_WordPtr.Text, 16);
            Num = Convert.ToByte(text_RWlen.Text);
            fPassWord = HexStringToByteArray(text_AccessCode2.Text);
            for (int p = 0; p < 10; p++)
            {
                fCmdRet = RWDev.ReadData_G2(ref fComAdr, EPC, ENum, Mem, WordPtr, Num, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, CardData, ref ferrorcode, frmcomportindex);
                if (fCmdRet == 0) break;
            }
            if (fCmdRet != 0)
            {

                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_read_tag_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_read_tag_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                byte[] daw = new byte[Num * 2];
                Array.Copy(CardData, daw, Num * 2);
                text_WriteData.Text = ByteArrayToHexString(daw);
                string strLog = ResourceCulture.GetString("log_read_tag_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btWrite_Click(object sender, EventArgs e)
        {
            byte WordPtr, ENum;
            byte WNum = 0;
            byte Mem = 0;
            string str = ""; ;
            byte[] CardData = new byte[320];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            if (checkBox1.Checked)
            {
                if ((maskadr_textbox.Text == "") || (maskLen_textBox.Text == "") || (maskData_textBox.Text == ""))
                {
                    return;
                }
                ENum = 255;
                if (R_EPC.Checked) MaskMem = 1;
                if (R_TID.Checked) MaskMem = 2;
                if (R_User.Checked) MaskMem = 3;
                MaskAdr = HexStringToByteArray(maskadr_textbox.Text);
                MaskLen = Convert.ToByte(maskLen_textBox.Text, 16);
                MaskData = HexStringToByteArray(maskData_textBox.Text);
            }
            else
            {
                if (check_selecttag.Checked)
                    str = text_epc.Text;
                else
                    str = "";
                ENum = Convert.ToByte(str.Length / 4);
            }
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            if (C_Reserve.Checked)
                Mem = 0;
            if (C_EPC.Checked)
                Mem = 1;
            if (C_TID.Checked)
                Mem = 2;
            if (C_User.Checked)
                Mem = 3;
            if (text_WordPtr.Text == "" || text_AccessCode2.Text.Length != 8)
            {
                return;
            }
            string epcstr = text_WriteData.Text;
            if (epcstr.Length % 4 != 0 || epcstr.Length == 0)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_input_by_word"), ResourceCulture.GetString("hint_info"));
                return;
            }
            WNum = Convert.ToByte(epcstr.Length / 4);
            byte[] Writedata = new byte[WNum * 2 + 1];
            Writedata = HexStringToByteArray(epcstr);
            WordPtr = (byte)Convert.ToInt32(text_WordPtr.Text, 16);
            fPassWord = HexStringToByteArray(text_AccessCode2.Text);
            if ((checkBox_pc.Checked) && (C_EPC.Checked))
            {
                WordPtr = 1;
                WNum = Convert.ToByte(epcstr.Length / 4 + 1);
                Writedata = HexStringToByteArray(textBox_pc.Text + epcstr);
            }
            for (int p = 0; p < 10; p++)
            {
                fCmdRet = RWDev.WriteData_G2(ref fComAdr, EPC, WNum, ENum, Mem, WordPtr, Writedata, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, ref ferrorcode, frmcomportindex);
                if (fCmdRet == 0) break;
            }
            if (fCmdRet != 0)
            {
                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_write_tag_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_write_tag_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_write_tag_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void checkBox_pc_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_pc.Checked && C_EPC.Checked)
            {
                text_WordPtr.Text = "0002";
                text_WordPtr.ReadOnly = true;
                int m, n;
                n = text_WriteData.Text.Length;
                if (n % 4 == 0)
                {
                    m = n / 4;
                    m = (m & 0x3F) << 3;
                    textBox_pc.Text = Convert.ToString(m, 16).PadLeft(2, '0') + "00";
                }
            }
            else
            {
                text_WordPtr.ReadOnly = false;
            }
        }

        private void text_WriteData_TextChanged(object sender, EventArgs e)
        {
            int m, n;
            n = text_WriteData.Text.Length;
            if ((checkBox_pc.Checked) && (n % 4 == 0) && (C_EPC.Checked))
            {
                m = n / 4;
                m = (m & 0x3F) << 3;
                textBox_pc.Text = Convert.ToString(m, 16).PadLeft(2, '0') + "00";
            }
        }

        private void C_EPC_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_pc.Checked)
            {
                text_WordPtr.Text = "0002";
                text_WordPtr.ReadOnly = true;
            }
            else
            {
                text_WordPtr.ReadOnly = false;
            }
        }

        private void btBlockWrite_Click(object sender, EventArgs e)
        {
            byte WordPtr, ENum;
            byte WNum = 0;
            byte Mem = 0;
            string str = ""; ;
            byte[] CardData = new byte[320];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            if (checkBox1.Checked)
            {
                if ((maskadr_textbox.Text == "") || (maskLen_textBox.Text == "") || (maskData_textBox.Text == ""))
                {
                    return;
                }
                ENum = 255;
                if (R_EPC.Checked) MaskMem = 1;
                if (R_TID.Checked) MaskMem = 2;
                if (R_User.Checked) MaskMem = 3;
                MaskAdr = HexStringToByteArray(maskadr_textbox.Text);
                MaskLen = Convert.ToByte(maskLen_textBox.Text, 16);
                MaskData = HexStringToByteArray(maskData_textBox.Text);
            }
            else
            {
                if (check_selecttag.Checked)
                    str = text_epc.Text;
                else
                    str = "";
                ENum = Convert.ToByte(str.Length / 4);
            }
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            if (C_Reserve.Checked)
                Mem = 0;
            if (C_EPC.Checked)
                Mem = 1;
            if (C_TID.Checked)
                Mem = 2;
            if (C_User.Checked)
                Mem = 3;
            if (text_WordPtr.Text == "" || text_AccessCode2.Text.Length != 8)
            {
                return;
            }
            string epcstr = text_WriteData.Text;
            if (epcstr.Length % 4 != 0 || epcstr.Length == 0)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_input_by_word"), ResourceCulture.GetString("hint_info"));
                return;
            }
            WNum = Convert.ToByte(epcstr.Length / 4);
            byte[] Writedata = new byte[WNum * 2 + 1];
            Writedata = HexStringToByteArray(epcstr);
            WordPtr = (byte)Convert.ToInt32(text_WordPtr.Text, 16);
            fPassWord = HexStringToByteArray(text_AccessCode2.Text);
            if ((checkBox_pc.Checked) && (C_EPC.Checked))
            {
                WordPtr = 1;
                WNum = Convert.ToByte(epcstr.Length / 4 + 1);
                Writedata = HexStringToByteArray(textBox_pc.Text + epcstr);
            }
            for (int p = 0; p < 10; p++)
            {
                fCmdRet = RWDev.BlockWrite_G2(ref fComAdr, EPC, WNum, ENum, Mem, WordPtr, Writedata, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, ref ferrorcode, frmcomportindex);
                if (fCmdRet == 0) break;
            }
            if (fCmdRet != 0)
            {
                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_write_block_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_write_block_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_write_block_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btBlockErase_Click(object sender, EventArgs e)
        {
            byte WordPtr, ENum;
            byte Num = 0;
            byte Mem = 0;
            string str = ""; ;
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            text_WriteData.Text = "";
            if (checkBox1.Checked)
            {
                if ((maskadr_textbox.Text == "") || (maskLen_textBox.Text == "") || (maskData_textBox.Text == ""))
                {
                    return;
                }
                ENum = 255;
                if (R_EPC.Checked) MaskMem = 1;
                if (R_TID.Checked) MaskMem = 2;
                if (R_User.Checked) MaskMem = 3;
                MaskAdr = HexStringToByteArray(maskadr_textbox.Text);
                MaskLen = Convert.ToByte(maskLen_textBox.Text, 16);
                MaskData = HexStringToByteArray(maskData_textBox.Text);
            }
            else
            {
                if (check_selecttag.Checked)
                    str = text_epc.Text;
                else
                    str = "";
                ENum = Convert.ToByte(str.Length / 4);
            }
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            if (C_Reserve.Checked)
                Mem = 0;
            if (C_EPC.Checked)
                Mem = 1;
            if (C_TID.Checked)
                Mem = 2;
            if (C_User.Checked)
                Mem = 3;
            if (text_WordPtr.Text == "" || text_RWlen.Text == "" || text_AccessCode2.Text.Length != 8)
            {
                return;
            }
            WordPtr = (byte)Convert.ToInt32(text_WordPtr.Text, 16);
            Num = Convert.ToByte(text_RWlen.Text);
            fPassWord = HexStringToByteArray(text_AccessCode2.Text);
            fCmdRet = RWDev.BlockErase_G2(ref fComAdr, EPC, ENum, Mem, WordPtr, Num, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {

                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_erase_block_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_erase_block_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_erase_block_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btSetProtectState_Click(object sender, EventArgs e)
        {
            byte select = 0;
            byte setprotect = 0;
            string str = "";
            byte ENum;
            byte[] CardData = new byte[320];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            if (checkBox1.Checked)
            {
                if ((maskadr_textbox.Text.Length != 4) || (maskLen_textBox.Text.Length != 2) || (maskData_textBox.Text.Length % 2 != 0) && (maskData_textBox.Text.Length == 0))
                {
                    MessageBox.Show(ResourceCulture.GetString("hint_mask_data_error"), ResourceCulture.GetString("hint_info"));
                    return;
                }
                ENum = 255;
                if (R_EPC.Checked) MaskMem = 1;
                if (R_TID.Checked) MaskMem = 2;
                if (R_User.Checked) MaskMem = 3;
                MaskAdr = HexStringToByteArray(maskadr_textbox.Text);
                MaskLen = Convert.ToByte(maskLen_textBox.Text, 16);
                MaskData = HexStringToByteArray(maskData_textBox.Text);
            }
            else
            {
                if (check_selecttag.Checked)
                    str = text_epc.Text;
                else
                    str = "";
                ENum = Convert.ToByte(str.Length / 4);
            }
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            if (Edit_AccessCode6.Text.Length != 8)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_password_length_not_8"), ResourceCulture.GetString("hint_info"));
                return;
            }
            fPassWord = HexStringToByteArray(Edit_AccessCode6.Text);
            if (P_kill.Checked)
                select = 0x00;
            else if (p_pass.Checked)
                select = 0x01;
            else if (P_EPC.Checked)
                select = 0x02;
            else if (P_TID.Checked)
                select = 0x03;
            else if (P_User.Checked)
                select = 0x04;

            if (NoProect2.Checked)
                setprotect = 0x00;
            else if (Proect2.Checked)
                setprotect = 0x02;
            else if (Always2.Checked)
            {
                setprotect = 0x01;
                if (MessageBox.Show(this, ResourceCulture.GetString("hint_unlock_forever"),
                    ResourceCulture.GetString("hint_info"), MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                    return;
            }
            else if (AlwaysNot2.Checked)
            {
                setprotect = 0x03;
                if (MessageBox.Show(this, ResourceCulture.GetString("hint_lock_forever"),
                    ResourceCulture.GetString("hint_info"), MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                    return;
            }
            if (checkBox_U9.Checked)
            {
                select = 255;
                setprotect = 255;
            }
            fCmdRet = RWDev.Lock_G2(ref fComAdr, EPC, ENum, select, setprotect, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {

                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_set_protect_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_set_protect_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_protect_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }

        }

        private void btDestroyCard_Click(object sender, EventArgs e)
        {
            string str = "";
            byte ENum;
            byte[] CardData = new byte[320];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];

            if (checkBox1.Checked)
            {
                if ((maskadr_textbox.Text.Length != 4) || (maskLen_textBox.Text.Length != 2) || (maskData_textBox.Text.Length % 2 != 0) && (maskData_textBox.Text.Length == 0))
                {
                    MessageBox.Show(ResourceCulture.GetString("hint_mask_data_error"), ResourceCulture.GetString("hint_info"));
                    return;
                }
                ENum = 255;
                if (R_EPC.Checked) MaskMem = 1;
                if (R_TID.Checked) MaskMem = 2;
                if (R_User.Checked) MaskMem = 3;
                MaskAdr = HexStringToByteArray(maskadr_textbox.Text);
                MaskLen = Convert.ToByte(maskLen_textBox.Text, 16);
                MaskData = HexStringToByteArray(maskData_textBox.Text);
            }
            else
            {
                if (check_selecttag.Checked)
                    str = text_epc.Text;
                else
                    str = "";
                ENum = Convert.ToByte(str.Length / 4);
            }
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            if (text_DestroyCode.Text.Length != 8)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_password_length_not_8"), ResourceCulture.GetString("hint_info"));
                return;
            }
            fPassWord = HexStringToByteArray(text_DestroyCode.Text);
            fCmdRet = RWDev.KillTag_G2(ref fComAdr, EPC, ENum, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {

                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_kill_tag_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_kill_tag_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_kill_tag_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btWriteEPC_G2_Click(object sender, EventArgs e)
        {
            byte[] WriteEPC = new byte[200];
            byte WriteEPClen;
            byte ENum;
            if (text_AccessCode3.Text.Length < 8)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_password_length_not_8"), ResourceCulture.GetString("hint_info"));
                return;
            }
            if ((text_WriteEPC.Text.Length % 4) != 0 || text_WriteEPC.Text.Length == 0)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_input_hex_data"), ResourceCulture.GetString("hint_info"));
                return;
            }
            WriteEPClen = Convert.ToByte(text_WriteEPC.Text.Length / 2);
            ENum = Convert.ToByte(text_WriteEPC.Text.Length / 4);
            byte[] EPC = new byte[ENum];
            EPC = HexStringToByteArray(text_WriteEPC.Text);
            fPassWord = HexStringToByteArray(text_AccessCode3.Text);
            fCmdRet = RWDev.WriteEPC_G2(ref fComAdr, fPassWord, EPC, ENum, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {

                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_write_epc_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_write_epc_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                if (comboBox_EPC.Items.IndexOf(text_WriteEPC.Text) == -1)
                    comboBox_EPC.Items.Add(text_WriteEPC.Text);
                string strLog = ResourceCulture.GetString("log_write_epc_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }

        }

        private void btSetReadProtect_G2_Click(object sender, EventArgs e)
        {
            string str = "";
            byte ENum;
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            if (checkBox1.Checked)
            {
                if ((maskadr_textbox.Text.Length != 4) || (maskLen_textBox.Text.Length != 2) || (maskData_textBox.Text.Length % 2 != 0) && (maskData_textBox.Text.Length == 0))
                {
                    MessageBox.Show(ResourceCulture.GetString("hint_mask_data_error"), ResourceCulture.GetString("hint_info"));
                    return;
                }
                ENum = 255;
                if (R_EPC.Checked) MaskMem = 1;
                if (R_TID.Checked) MaskMem = 2;
                if (R_User.Checked) MaskMem = 3;
                MaskAdr = HexStringToByteArray(maskadr_textbox.Text);
                MaskLen = Convert.ToByte(maskLen_textBox.Text, 16);
                MaskData = HexStringToByteArray(maskData_textBox.Text);
            }
            else
            {
                if (check_selecttag.Checked)
                    str = text_epc.Text;
                else
                    str = "";
                ENum = Convert.ToByte(str.Length / 4);
            }
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            if (text_AccessCode4.Text.Length != 8)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_password_length_not_8"), ResourceCulture.GetString("hint_info"));
                return;
            }
            fPassWord = HexStringToByteArray(text_AccessCode4.Text);
            fCmdRet = RWDev.SetPrivacyByEPC_G2(ref fComAdr, EPC, ENum, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {

                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_privacy_by_epc_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_privacy_by_epc_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_privacy_by_epc_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btSetMultiReadProtect_G2_Click(object sender, EventArgs e)
        {
            if (text_AccessCode4.Text.Length != 8)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_password_length_not_8"), ResourceCulture.GetString("hint_info"));
                return;
            }
            fPassWord = HexStringToByteArray(text_AccessCode4.Text);
            fCmdRet = RWDev.SetPrivacyWithoutEPC_G2(ref fComAdr, fPassWord, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {

                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_privacy_without_epc_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("Set privacy without EPC failed: ") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_privacy_without_epc_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btRemoveReadProtect_G2_Click(object sender, EventArgs e)
        {
            if (text_AccessCode4.Text.Length != 8)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_password_length_not_8"), ResourceCulture.GetString("hint_info"));
                return;
            }
            fPassWord = HexStringToByteArray(text_AccessCode4.Text);
            fCmdRet = RWDev.ResetPrivacy_G2(ref fComAdr, fPassWord, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {

                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_remove_privacy_without_epc_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_remove_privacy_without_epc_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_remove_privacy_without_epc_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btCheckReadProtected_G2_Click(object sender, EventArgs e)
        {
            byte readpro = 2;
            fCmdRet = RWDev.CheckPrivacy_G2(ref fComAdr, ref readpro, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {

                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_check_privacy_without_epc_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_check_privacy_without_epc_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = "";
                if (readpro == 0)
                    strLog = ResourceCulture.GetString("log_check_privacy_without_pwd_failed");
                if (readpro == 1)
                    strLog = ResourceCulture.GetString("log_check_privacy_without_pwd_01_failed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btSetEASAlarm_G2_Click(object sender, EventArgs e)
        {
            byte EAS = 0;
            byte ENum;
            string str = "";
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            text_WriteData.Text = "";
            if (checkBox1.Checked)
            {
                if ((maskadr_textbox.Text == "") || (maskLen_textBox.Text == "") || (maskData_textBox.Text == ""))
                {
                    return;
                }
                ENum = 255;
                if (R_EPC.Checked) MaskMem = 1;
                if (R_TID.Checked) MaskMem = 2;
                if (R_User.Checked) MaskMem = 3;
                MaskAdr = HexStringToByteArray(maskadr_textbox.Text);
                MaskLen = Convert.ToByte(maskLen_textBox.Text, 16);
                MaskData = HexStringToByteArray(maskData_textBox.Text);
            }
            else
            {
                if (check_selecttag.Checked)
                    str = text_epc.Text;
                else
                    str = "";
                ENum = Convert.ToByte(str.Length / 4);
            }
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            if (text_AccessCode5.Text.Length != 8)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_password_length_not_8"), ResourceCulture.GetString("hint_info"));
                return;
            }
            fPassWord = HexStringToByteArray(text_AccessCode5.Text);
            if (Alarm_G2.Checked)
                EAS = 1;
            else
                EAS = 0;
            fCmdRet = RWDev.EASConfigure_G2(ref fComAdr, EPC, ENum, fPassWord, EAS, MaskMem, MaskAdr, MaskLen, MaskData, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_alarm_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = "";
                if (Alarm_G2.Checked)
                    strLog = ResourceCulture.GetString("log_set_alarm_succeed");
                else
                    strLog = ResourceCulture.GetString("log_clear_alarm_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }

        }

        private void btCheckEASAlarm_Click(object sender, EventArgs e)
        {
            timer_EAS.Enabled = !timer_EAS.Enabled;
            if (!timer_EAS.Enabled)
            {
                pictureBox2.Visible = false;
                btCheckEASAlarm.Text = ResourceCulture.GetString("btn_eas_alarm");
                btCheckEASAlarm.BackColor = Color.Transparent;
            }
            else
            {
                fIsInventoryScan = false;
                btCheckEASAlarm.Text = ResourceCulture.GetString("btn_stop");
                btCheckEASAlarm.BackColor = Color.Indigo;
            }
        }

        private void timer_EAS_Tick(object sender, EventArgs e)
        {
            if (fIsInventoryScan)
                return;
            fIsInventoryScan = true;
            fCmdRet = RWDev.EASAlarm_G2(ref fComAdr, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_no_alarm_detect");
                WriteLog(lrtxtLog, strLog, 1);
                pictureBox2.Visible = false;
            }
            else
            {
                pictureBox2.Visible = true;
                string strLog = ResourceCulture.GetString("log_alarm_detect");
                WriteLog(lrtxtLog, strLog, 0);
            }
            fIsInventoryScan = false;
        }

        private void btInventory6B_Click(object sender, EventArgs e)
        {
            Timer_Test_6B.Enabled = !Timer_Test_6B.Enabled;
            if (!Timer_Test_6B.Enabled)
            {
                btInventory6B.Text = ResourceCulture.GetString("btn_inventory_start");
                btInventory6B.BackColor = Color.Transparent;
            }
            else
            {
                fisinventoryscan_6B = false;
                ListView_ID_6B.Items.Clear();
                btInventory6B.BackColor = Color.Indigo;
                btInventory6B.Text = ResourceCulture.GetString("btn_inventory_stop");
            }
        }
        public void ChangeSubItem1(ListViewItem ListItem, int subItemIndex, string ItemText, string ant, string RSSI)
        {
            if (subItemIndex == 1)
            {
                if (ListItem.SubItems[subItemIndex].Text != ItemText)
                {
                    ListItem.SubItems[subItemIndex].Text = ItemText;
                    ListItem.SubItems[subItemIndex + 2].Text = "1";
                    ListItem.SubItems[subItemIndex + 1].Text = ant;
                }
                else
                {
                    ListItem.SubItems[subItemIndex + 2].Text = Convert.ToString(Convert.ToUInt32(ListItem.SubItems[subItemIndex + 2].Text) + 1);
                    if ((Convert.ToUInt32(ListItem.SubItems[subItemIndex + 2].Text) > 9999))
                        ListItem.SubItems[subItemIndex + 2].Text = "1";
                    ListItem.SubItems[subItemIndex + 1].Text = Convert.ToString(Convert.ToInt32(ListItem.SubItems[subItemIndex + 1].Text, 2) | Convert.ToInt32(ant, 2), 2).PadLeft(4, '0');

                }
                ListItem.SubItems[subItemIndex + 3].Text = RSSI;
            }
        }
        private void Inventory_6B()
        {
            int CardNum = 0;
            byte[] ID_6B = new byte[2000];
            byte[] ID2_6B = new byte[5000];
            bool isonlistview;
            string temps;
            string s, ss, sID;
            ListViewItem aListItem = new ListViewItem();
            int i, j;
            byte Condition = 0;
            byte StartAddress;
            byte mask = 0;
            byte[] ConditionContent = new byte[300];
            byte ant = 0;
            if (rb_single.Checked)
            {
                fCmdRet = RWDev.InventorySingle_6B(ref fComAdr, ref ant, ID_6B, frmcomportindex);
                if (fCmdRet == 0)
                {
                    byte[] daw = new byte[10];
                    Array.Copy(ID_6B, daw, 10);
                    temps = ByteArrayToHexString(daw);
                    string RSSI = daw[9].ToString();
                    temps = temps.Substring(2, 16);

                    if (!list.Contains(temps))
                    {
                        CardNum1 = CardNum1 + 1;
                        list.Add(temps);
                    }
                    string sant = Convert.ToString(ant, 2).PadLeft(4, '0');
                    isonlistview = false;
                    for (i = 0; i < ListView_ID_6B.Items.Count; i++)     //判断是否在ListView列表内
                    {
                        if (temps == ListView_ID_6B.Items[i].SubItems[1].Text)
                        {
                            aListItem = ListView_ID_6B.Items[i];
                            ChangeSubItem1(aListItem, 1, temps, sant, RSSI);
                            isonlistview = true;
                            break;
                        }
                    }
                    if (!isonlistview)
                    {
                        aListItem = ListView_ID_6B.Items.Add((ListView_ID_6B.Items.Count + 1).ToString());
                        aListItem.SubItems.Add("");
                        aListItem.SubItems.Add("");
                        aListItem.SubItems.Add("");
                        aListItem.SubItems.Add("");
                        aListItem.SubItems.Add("");
                        s = temps;
                        ChangeSubItem1(aListItem, 1, s, sant, RSSI);
                    }
                }
            }
            if (rb_mutiple.Checked)
            {
                Condition = 1;
                ss = "0000000000000000";//4种条件这里选择的是非全0的标签
                byte[] daw = HexStringToByteArray(ss);
                mask = 0xFF;
                StartAddress = 0;
                CardNum = 0;
                fCmdRet = RWDev.InventoryMultiple_6B(ref fComAdr, Condition, StartAddress, mask, daw, ref ant, ID2_6B, ref CardNum, frmcomportindex);
                if ((fCmdRet == 0x15) | (fCmdRet == 0x16) | (fCmdRet == 0x17) | (fCmdRet == 0x18) | (fCmdRet == 0xFB))
                {
                    byte[] daw1 = new byte[CardNum * 10];
                    Array.Copy(ID2_6B, daw1, CardNum * 10);
                    temps = ByteArrayToHexString(daw1);
                    string sant = Convert.ToString(ant, 2).PadLeft(4, '0');
                    for (i = 0; i < CardNum; i++)
                    {
                        sID = temps.Substring(20 * i + 2, 16);
                        string RSSI = temps.Substring(20 * i + 18, 2);
                        RSSI = Convert.ToByte(RSSI, 16).ToString();
                        if ((sID.Length) != 16)
                            return;
                        if (CardNum == 0)
                            return;
                        isonlistview = false;
                        for (j = 0; j < ListView_ID_6B.Items.Count; j++)     //判断是否在Listview列表内
                        {
                            if (sID == ListView_ID_6B.Items[j].SubItems[1].Text)
                            {
                                aListItem = ListView_ID_6B.Items[j];
                                ChangeSubItem1(aListItem, 1, sID, sant, RSSI);
                                isonlistview = true;
                                break;
                            }
                        }
                        if (!isonlistview)
                        {
                            aListItem = ListView_ID_6B.Items.Add((ListView_ID_6B.Items.Count + 1).ToString());
                            aListItem.SubItems.Add("");
                            aListItem.SubItems.Add("");
                            aListItem.SubItems.Add("");
                            aListItem.SubItems.Add("");
                            aListItem.SubItems.Add("");
                            s = sID;
                            ChangeSubItem1(aListItem, 1, s, sant, RSSI);
                        }
                    }
                }
            }
            WriteLog(lrtxtLog, ResourceCulture.GetString("log_18000_6B_inventory"), 0);
        }
        private void Timer_Test_6B_Tick(object sender, EventArgs e)
        {
            if (fisinventoryscan_6B)
                return;
            fisinventoryscan_6B = true;
            Inventory_6B();
            fisinventoryscan_6B = false;
        }

        private void ListView_ID_6B_DoubleClick(object sender, EventArgs e)
        {
            if (this.ListView_ID_6B.SelectedIndices.Count > 0 && this.ListView_ID_6B.SelectedIndices[0] != -1)
            {
                text_6BUID.Text = ListView_ID_6B.SelectedItems[0].SubItems[1].Text;
            }
        }
        //E004000085D94502
        private void btRead6B_Click(object sender, EventArgs e)
        {
            string temp, temps;
            byte[] CardData = new byte[320];
            byte[] ID_6B = new byte[8];
            byte Num, StartAddress;
            if (text_6BUID.Text == "")
            {
                MessageBox.Show(ResourceCulture.GetString("hint_select_tag"));
                return;
            }
            temp = text_6BUID.Text;
            ID_6B = HexStringToByteArray(temp);
            if (text_R6BAddr.Text == "")
                return;
            StartAddress = Convert.ToByte(text_R6BAddr.Text, 16);
            if (text_R6BLen.Text == "")
                return;
            Num = Convert.ToByte(text_R6BLen.Text, 16);
            fCmdRet = RWDev.ReadData_6B(ref fComAdr, ID_6B, StartAddress, Num, CardData, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_read_data_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_read_data_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                byte[] data = new byte[Num];
                Array.Copy(CardData, data, Num);
                temps = ByteArrayToHexString(data);
                text_R6B.Text = temps;
                string strLog = ResourceCulture.GetString("log_read_data_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btWrite6B_Click(object sender, EventArgs e)
        {
            string temp;
            byte[] CardData = new byte[320];
            byte[] ID_6B = new byte[8];
            byte StartAddress;
            byte Writedatalen;
            int writtenbyte = 0;
            if (text_6BUID.Text == "")
            {
                MessageBox.Show(ResourceCulture.GetString("hint_select_tag"));
                return;
            }
            // text_6BUID.Text = "E004000085D94502";
            temp = text_6BUID.Text;
            ID_6B = HexStringToByteArray(temp);
            if (text_W6BAddr.Text == "")
                return;
            StartAddress = Convert.ToByte(text_W6BAddr.Text, 16);
            if (text_W6BLen.Text == "")
                return;
            Writedatalen = Convert.ToByte(text_W6BLen.Text, 16);

            if ((text_W6B.Text == "") | ((text_W6B.Text.Length / 2) != Writedatalen) | ((text_W6B.Text.Length % 2) != 0))
                return;
            byte[] Writedata = new byte[Writedatalen];
            Writedata = HexStringToByteArray(text_W6B.Text);
            fCmdRet = RWDev.WriteData_6B(ref fComAdr, ID_6B, StartAddress, Writedata, Writedatalen, ref writtenbyte, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_write_data_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_write_data_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_write_data_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }

        }

        private void text_W6BLen_TextChanged(object sender, EventArgs e)
        {
            text_W6B.MaxLength = Convert.ToInt32(text_W6BLen.Text, 16) * 2;
        }

        private void btLock6B_Click(object sender, EventArgs e)
        {
            byte Address;
            string temps;
            byte[] ID_6B = new byte[8];
            if (text_6BUID.Text == "")
            {
                MessageBox.Show(ResourceCulture.GetString("hint_select_tag"));
                return;
            }
            temps = text_6BUID.Text;
            ID_6B = HexStringToByteArray(temps);
            if (text_lock6b.Text == "")
                return;
            Address = Convert.ToByte(text_lock6b.Text,16);
            if (MessageBox.Show(this, ResourceCulture.GetString("hint_lock_forever"),
                ResourceCulture.GetString("hint_info"), MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                return;
            fCmdRet = RWDev.Lock_6B(ref fComAdr, ID_6B, Address, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_lock_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_lock_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_lock_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }

        }

        private void btCheckLock6B_Click(object sender, EventArgs e)
        {
            byte Address, ReLockState = 2;
            string temps;
            byte[] ID_6B = new byte[8];
            if (text_6BUID.Text == "")
            {
                MessageBox.Show(ResourceCulture.GetString("hint_select_tag"));
                return;
            }
            temps = text_6BUID.Text;
            ID_6B = HexStringToByteArray(temps);
            if (text_checkaddr.Text == "")
                return;
            Address = Convert.ToByte(text_checkaddr.Text, 16);
            fCmdRet = RWDev.CheckLock_6B(ref fComAdr, ID_6B, Address, ref ReLockState, ref ferrorcode, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_check_lock_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_check_lock_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = "";
                if (ReLockState == 0)
                    text_Statu6B.Text = ResourceCulture.GetString("log_byte_unlocked");
                if (ReLockState == 1)
                    text_Statu6B.Text = ResourceCulture.GetString("log_byte_locked");
                strLog = ResourceCulture.GetString("log_check_lock_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }

        }

       

        /// <summary>
        /// 将Device List中所记录设备显示至DeviceListView控件;
        /// </summary>
        private void ReflashDeviceListView(List<DeviceClass> deviceList)
        {
            this.DeviceListView.Items.Clear();
            foreach (DeviceClass device in deviceList)
            {
                IPAddress ipAddr = getIPAddress(device.DeviceIP);
                ListViewItem deviceListViewItem = new ListViewItem(new string[] { device.DeviceName, ipAddr.ToString(), device.DeviceMac });
                deviceListViewItem.ImageIndex = 0;
                this.DeviceListView.Items.Add(deviceListViewItem);
            }
        }

        /// <summary>
        /// 将Device List中所记录设备显示至DeviceListView控件;
        /// </summary>
        private void ClearDeviceListView()
        {
            DevControl.tagErrorCode eCode;
            List<DeviceClass> deviceList = DevList;

            foreach (DeviceClass device in deviceList)
            {
                eCode = DevControl.DM_FreeDevice(device.DevHandle);
                Debug.Assert(eCode == DevControl.tagErrorCode.DM_ERR_OK);
            }
            //清空设备列表，并清空对应显示控件；
            DevList.Clear();
            ReflashDeviceListView(DevList);
        }

        /// <summary>
        /// 搜索设备，然后将记录搜索结果的DevList显示至DeviceListView控件;
        /// </summary>
        private bool SearchDevice(uint targetIP)
        {
            ClearDeviceListView();
            DevControl.tagErrorCode eCode = DevControl.DM_SearchDevice(targetIP, 1500);
            if (eCode == DevControl.tagErrorCode.DM_ERR_OK)
            {
                ReflashDeviceListView(DevList);
                return true;
            }
            else
            {
                //异常处理；
                string errMsg = ErrorHandling.HandleError(eCode);
                System.Windows.Forms.MessageBox.Show(errMsg);
                return false;
            }
        }

        /// <summary>
        /// 配置选定设备，开启对应配置窗体;
        /// </summary>
        private void ConfigSelectedDevice()
        {
            if (this.DeviceListView.SelectedIndices.Count > 0
                && this.DeviceListView.SelectedIndices[0] != -1)
            {
                //通过用户在显示控件中选择的索引值，在查找其所对应的设备对象；
                DeviceClass currentDevice = DevList[DeviceListView.SelectedIndices[0]];

                LoginForm loginform = new LoginForm();
                DialogResult result = loginform.ShowDialog();
                if (result == DialogResult.OK)
                {
                    DevControl.tagErrorCode eCode = currentDevice.Login(loginform.UserName, loginform.Password);
                    if (eCode == DevControl.tagErrorCode.DM_ERR_OK)
                    {
                        //记录当前选择设备对象，作为父窗体属性传递至新开启的子配置窗体；
                        this.SelectedDevice = currentDevice;
                        ConfigForm deviceConfigForm = new ConfigForm(this.SelectedDevice);
                        deviceConfigForm.ShowDialog(this);
                        deviceConfigForm.Dispose();
                    }
                    else
                    {
                        //异常处理；
                        string errMsg = ErrorHandling.HandleError(eCode);
                        System.Windows.Forms.MessageBox.Show(errMsg);
                    }
                }

                loginform.Dispose();
            }
        }
        private void searchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //使用广播搜索设备；
            SearchDevice(DeviceClass.Broadcast);
        }

        private void configToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConfigSelectedDevice();
        }

        private void clearToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClearDeviceListView();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //关闭主窗体并退出程序；
            this.Close();
        }

        private void iEToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //开启IE访问目标设备；
            try
            {
                if (DeviceListView.SelectedIndices.Count > 0
                    && DeviceListView.SelectedIndices[0] != -1)
                {
                    DeviceClass currentDevice = DevList[DeviceListView.SelectedIndices[0]];
                    System.Diagnostics.Process.Start("iexplore.exe", "HTTP://" + getIPAddress(currentDevice.DeviceIP).ToString());
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
            }
        }

        private void telnetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //开启TELNET客户端访问目标设备；
            try
            {
                if (DeviceListView.SelectedIndices.Count > 0
                    && DeviceListView.SelectedIndices[0] != -1)
                {
                    DeviceClass currentDevice = DevList[DeviceListView.SelectedIndices[0]];
                    System.Diagnostics.Process.Start("telnet.exe", getIPAddress(currentDevice.DeviceIP).ToString());
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
            }
        }

        private void pingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (DeviceListView.SelectedIndices.Count > 0
                    && DeviceListView.SelectedIndices[0] != -1)
                {
                    DeviceClass currentDevice = DevList[DeviceListView.SelectedIndices[0]];
                    System.Diagnostics.Process.Start("ping.exe", getIPAddress(currentDevice.DeviceIP).ToString() + " -t");
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            DevControl.tagErrorCode eCode = DevControl.DM_DeInit();
            if (eCode != DevControl.tagErrorCode.DM_ERR_OK)
            {
                ErrorHandling.HandleError(eCode);
            }
        }

        private void DeviceListView_DoubleClick(object sender, EventArgs e)
        {
            ConfigSelectedDevice();
        }

        private void btFlashROM_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(this, ResourceCulture.GetString("hint_update"),
                ResourceCulture.GetString("hint_info"), MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                return;
            fCmdRet = RWDev.SetFlashRom(ref fComAdr, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_switch_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_switch_succeed");
                WriteLog(lrtxtLog, strLog, 0);
                if (frmcomportindex > 0 && frmcomportindex < 256)
                {
                    btDisConnect232_Click(null, null);
                }
            }
        }

        private void tabPage8_Click(object sender, EventArgs e)
        {

        }

        public class ctcplist//存储100客户端信息.
        {
            public Socket[] tempSocket = new Socket[100];
            public string[] ip = new string[100];
            public int[] port = new int[100];
        }
        ctcplist tcplist = new ctcplist();
        Thread listenThread = null;//监听进程
        Socket newsock = null;
        private void StartListening() //main listening thread
        {
            int port = Convert.ToInt32(stcpport.Text);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, port);//绑定端口
            newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//tcp协议
            newsock.Bind(ipep);
            newsock.Listen(10);
            while (true)
            {
                try
                {
                    Socket client = newsock.Accept();//等待TCP客户端的链接请求
                    //查找空缺，插入信息
                    int m = 0;
                    for (m = 0; m < 100; m++)
                    {
                        if (tcplist.ip[m] == null)
                        {
                            int nport = ((System.Net.IPEndPoint)client.RemoteEndPoint).Port;
                            IPAddress ip = ((System.Net.IPEndPoint)client.RemoteEndPoint).Address;
                            tcplist.tempSocket[m] = client;
                            tcplist.ip[m] = ip.ToString();
                            tcplist.port[m] = nport;
                            this.Invoke((EventHandler)delegate
                            {
                                listtcp.Items.Add(ip.ToString() + ":" + nport.ToString());
                            });

                            break;
                        }
                    }
                    ParameterizedThreadStart ParStart = new ParameterizedThreadStart(ServiceClient);
                    Thread clientService = new Thread(ParStart);
                    clientService.IsBackground = true;
                    object o = client;
                    clientService.Start(o);
                }
                catch (System.Exception ex)
                {
                    ex.ToString();
                    break;
                }
            }
        }

        private void btListen_Click(object sender, EventArgs e)
        {
            //创建监听进程
            stcpport.Enabled = false;
            btListen.Enabled = false;
            listenThread = new Thread(new ThreadStart(StartListening));
            listenThread.IsBackground = true;
            listenThread.Start();
        }
        public static string ByteArrayToHexString2(byte[] data)
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadLeft(3, ' '));
            return sb.ToString().ToUpper();

        }
        public void ServiceClient(object ParObject)
        {
            Socket tempSocket = (Socket)ParObject;
            IPEndPoint newclient = (IPEndPoint)tempSocket.RemoteEndPoint;

            //  NetworkStream ns = new NetworkStream(tempSocket);
            //  StreamReader sr = new StreamReader(ns);
            byte[] myReadBuffer = new byte[1024];
            IPAddress ip = (newclient).Address;
            int nport = (newclient).Port;
            int count = 0;
            string temp = "";
            while (true)
            {
                try
                {
                    count = tempSocket.Receive(myReadBuffer);
                    if (count > 0)
                    {
                        byte[] data = new byte[count];
                        Array.Copy(myReadBuffer, data, count);
                        temp = ByteArrayToHexString2(data);
                        this.Invoke((EventHandler)delegate
                        {
                            stcprecv.AppendText(Environment.NewLine + ip.ToString() + ":" + nport.ToString() + " " + temp);
                            stcprecv.Select(stcprecv.TextLength, 0);
                            stcprecv.ScrollToCaret();
                        });
                    }
                    else
                    {
                        this.Invoke((EventHandler)delegate
                        {
                            int m = 0;
                            for (m = 0; m < 100; m++)
                            {
                                if (tcplist.ip[m] == ip.ToString() && (tcplist.port[m] == nport))//找到
                                {
                                    int n = listtcp.Items.IndexOf(ip.ToString() + ":" + nport.ToString());
                                    listtcp.Items.RemoveAt(n);
                                    tcplist.tempSocket[m].Close();
                                    tcplist.ip[m] = null;
                                    tcplist.port[m] = 0;
                                    tcplist.tempSocket[m] = null;
                                    break;
                                }
                            }
                        });
                        break;
                    }
                }
                catch
                {
                    //查找断开连接的设备IP
                    this.Invoke((EventHandler)delegate
                    {
                        int m = 0;
                        for (m = 0; m < 100; m++)
                        {
                            if (tcplist.ip[m] == ip.ToString() && (tcplist.port[m] == nport))//找到
                            {
                                int n = listtcp.Items.IndexOf(ip.ToString() + ":" + nport.ToString());
                                listtcp.Items.RemoveAt(n);
                                tcplist.tempSocket[m].Close();
                                tcplist.ip[m] = null;
                                tcplist.port[m] = 0;
                                tcplist.tempSocket[m] = null;
                                break;
                            }
                        }
                    });
                    break;
                }
            }
        }

        private void btStop_Click(object sender, EventArgs e)
        {
            int m = 0;
            for (m = 0; m < 100; m++)
            {
                if (tcplist.tempSocket[m] != null)//找到
                {

                    int n = listtcp.Items.IndexOf(tcplist.ip[m] + ":" + tcplist.port[m].ToString());
                    listtcp.Items.RemoveAt(n);
                    tcplist.tempSocket[m].Close();
                    tcplist.ip[m] = null;
                    tcplist.port[m] = 0;
                    tcplist.tempSocket[m] = null;
                }
            }

            if (newsock != null)
                newsock.Close();
            if (listenThread != null)
                listenThread.Abort();

            stcpport.Enabled = true;
            btListen.Enabled = true;
        }

        Socket m_client;
        Thread clientThread = null;//接收数据线程
        private void bttcpconnect_Click(object sender, EventArgs e)
        {
            try
            {
                string ip = tcpremoteIp.IpAddressStr;
                int nipport = Convert.ToInt32(remotePort.Text);
                m_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ip), nipport);
                m_client.Connect(ie);
                if (m_client.Connected)
                {
                    tcpremoteIp.Enabled = false;
                    remotePort.Enabled = false;
                    bttcpconnect.Enabled = false;//连接成功创建接收数据线程
                    bttcpsend.Enabled = true;
                    clientThread = new Thread(new ThreadStart(StartRead));
                    clientThread.IsBackground = true;
                    clientThread.Start();
                }
                else
                {
                    tcpremoteIp.Enabled = true;
                    remotePort.Enabled = true;
                    bttcpconnect.Enabled = true;
                    bttcpsend.Enabled = false;
                }

            }
            catch (SocketException ex)
            {
                ex.ToString();
                tcpremoteIp.Enabled = true;
                remotePort.Enabled = true;
                bttcpconnect.Enabled = true;
                bttcpsend.Enabled = false;
            }
        }
        private void StartRead()
        {
            byte[] buffs = new byte[2048];
            IPEndPoint newclient = (IPEndPoint)m_client.RemoteEndPoint;
            IPAddress ip = (newclient).Address;
            int nport = (newclient).Port;
            while (true)
            {
                try
                {
                    int count = m_client.Receive(buffs);
                    if (count > 0)
                    {
                        byte[] data = new byte[count];
                        Array.Copy(buffs, data, count);
                        string temp = ByteArrayToHexString2(data);
                        this.Invoke((EventHandler)delegate
                        {
                            ctctrecv.AppendText(Environment.NewLine + ip.ToString() + ":" + nport.ToString() + " " + temp);
                            ctctrecv.Select(stcprecv.TextLength, 0);
                            ctctrecv.ScrollToCaret();
                        });
                    }
                }
                catch (System.Exception ex)
                {
                    ex.ToString();
                    if (m_client.Connected)
                    {
                        m_client.Shutdown(SocketShutdown.Both);
                        m_client.Close();
                    }
                    this.Invoke((EventHandler)delegate
                    {
                        tcpremoteIp.Enabled = true;
                        remotePort.Enabled = true;
                        bttcpconnect.Enabled = true;
                    });
                    break;
                }
            }
        }

        private void bttcpsend_Click(object sender, EventArgs e)
        {
            if (m_client.Connected)
            {
                string temp = ctctsend.Text.Replace(" ", "");
                if (temp == "") return;
                if (temp.Length % 2 != 0)
                    temp = temp + "0";
                byte[] buff = new byte[1024];
                buff = HexStringToByteArray(temp);
                int m = m_client.Send(buff);
            }
        }

        private void bttcpdisconnect_Click(object sender, EventArgs e)
        {
            if (m_client.Connected)
            {
                m_client.Shutdown(SocketShutdown.Both);
                m_client.Close();
                clientThread.Abort();
                tcpremoteIp.Enabled = true;
                remotePort.Enabled = true;
                bttcpconnect.Enabled = true;
                bttcpsend.Enabled = false;
            }
        }

        private void com_S_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (com_S.SelectedIndex > 1)
            {
                check_num.Enabled = true;
            }
            else
            {
                check_num.Enabled = false;
            }
            if (com_S.SelectedIndex == 4)
            {
                group_ant1.Enabled = false;
                com_scantime.Enabled = false;
            }
            else
            {
                group_ant1.Enabled = true;
                com_scantime.Enabled = true;
            }
        }

        private void btExtRead_Click(object sender, EventArgs e)
        {
            byte ENum;
            byte Num = 0;
            byte Mem = 0;
            byte[] WordPtr = new byte[2];
            string str = ""; ;
            byte[] CardData = new byte[320];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            text_WriteData.Text = "";
            if (checkBox1.Checked)
            {
                if ((maskadr_textbox.Text == "") || (maskLen_textBox.Text == "") || (maskData_textBox.Text == ""))
                {
                    return;
                }
                ENum = 255;
                if (R_EPC.Checked) MaskMem = 1;
                if (R_TID.Checked) MaskMem = 2;
                if (R_User.Checked) MaskMem = 3;
                MaskAdr = HexStringToByteArray(maskadr_textbox.Text);
                MaskLen = Convert.ToByte(maskLen_textBox.Text, 16);
                MaskData = HexStringToByteArray(maskData_textBox.Text);
            }
            else
            {
                if (check_selecttag.Checked)
                    str = text_epc.Text;
                else
                    str = "";
                ENum = Convert.ToByte(str.Length / 4);
            }
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            if (C_Reserve.Checked)
                Mem = 0;
            if (C_EPC.Checked)
                Mem = 1;
            if (C_TID.Checked)
                Mem = 2;
            if (C_User.Checked)
                Mem = 3;
            if (text_WordPtr.Text == "" || text_RWlen.Text == "" || text_AccessCode2.Text.Length != 8)
            {
                return;
            }
            WordPtr = HexStringToByteArray(text_WordPtr.Text);
            Num = Convert.ToByte(text_RWlen.Text);
            fPassWord = HexStringToByteArray(text_AccessCode2.Text);
            for (int p = 0; p < 10; p++)
            {
                fCmdRet = RWDev.ExtReadData_G2(ref fComAdr, EPC, ENum, Mem, WordPtr, Num, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, CardData, ref ferrorcode, frmcomportindex);
                if (fCmdRet == 0) break;
            }
            if (fCmdRet != 0)
            {

                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_ext_read_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_ext_read_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                byte[] daw = new byte[Num * 2];
                Array.Copy(CardData, daw, Num * 2);
                text_WriteData.Text = ByteArrayToHexString(daw);
                string strLog = ResourceCulture.GetString("log_ext_read_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btExtWrite_Click(object sender, EventArgs e)
        {
            byte ENum;
            byte WNum = 0;
            byte Mem = 0;
            string str = "";
            byte[] WordPtr = new byte[2];
            byte[] CardData = new byte[320];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            if (checkBox1.Checked)
            {
                if ((maskadr_textbox.Text == "") || (maskLen_textBox.Text == "") || (maskData_textBox.Text == ""))
                {
                    return;
                }
                ENum = 255;
                if (R_EPC.Checked) MaskMem = 1;
                if (R_TID.Checked) MaskMem = 2;
                if (R_User.Checked) MaskMem = 3;
                MaskAdr = HexStringToByteArray(maskadr_textbox.Text);
                MaskLen = Convert.ToByte(maskLen_textBox.Text, 16);
                MaskData = HexStringToByteArray(maskData_textBox.Text);
            }
            else
            {
                if (check_selecttag.Checked)
                    str = text_epc.Text;
                else
                    str = "";
                ENum = Convert.ToByte(str.Length / 4);
            }
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            if (C_Reserve.Checked)
                Mem = 0;
            if (C_EPC.Checked)
                Mem = 1;
            if (C_TID.Checked)
                Mem = 2;
            if (C_User.Checked)
                Mem = 3;
            if (text_WordPtr.Text == "" || text_AccessCode2.Text.Length != 8)
            {
                return;
            }
            string epcstr = text_WriteData.Text;
            if (epcstr.Length % 4 != 0 || epcstr.Length == 0)
            {
                MessageBox.Show(ResourceCulture.GetString("hint_input_by_word"), ResourceCulture.GetString("hint_info"));
                return;
            }
            WNum = Convert.ToByte(epcstr.Length / 4);
            byte[] Writedata = new byte[WNum * 2 + 1];
            Writedata = HexStringToByteArray(epcstr);
            WordPtr = HexStringToByteArray(text_WordPtr.Text);
            fPassWord = HexStringToByteArray(text_AccessCode2.Text);
            if ((checkBox_pc.Checked) && (C_EPC.Checked))
            {
                WordPtr = HexStringToByteArray("0001");
                WNum = Convert.ToByte(epcstr.Length / 4 + 1);
                Writedata = HexStringToByteArray(textBox_pc.Text + epcstr);
            }
            for (int p = 0; p < 10; p++)
            {
                fCmdRet = RWDev.ExtWriteData_G2(ref fComAdr, EPC, WNum, ENum, Mem, WordPtr, Writedata, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, ref ferrorcode, frmcomportindex);
                if (fCmdRet == 0) break;
            }
            if (fCmdRet != 0)
            {
                string strLog = "";
                if (fCmdRet == 0xFC)
                    strLog = ResourceCulture.GetString("log_ext_write_fc_failed") + Convert.ToString(ferrorcode, 16) + "(" + GetErrorCodeDesc(ferrorcode) + ")";
                else
                    strLog = ResourceCulture.GetString("log_ext_write_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_ext_write_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btSetMaxtime_Click(object sender, EventArgs e)
        {
            byte Scantime = 0;
            Scantime = Convert.ToByte(comboBox_maxtime.SelectedIndex);
            fCmdRet = RWDev.SetInventoryScanTime(ref fComAdr, Scantime, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_max_time_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_max_time_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

    
        

   
    
        private void btStartMactive_Click(object sender, EventArgs e)
        {

            timer_RealTime.Enabled = !timer_RealTime.Enabled;
            if (!timer_RealTime.Enabled)
            {
                btStartMactive.Text = ResourceCulture.GetString("btn_inventory_start");
                btStartMactive.BackColor = Color.Transparent;
            }
            else
            {
                fInventory_EPC_List = "";
                total_time = System.Environment.TickCount;
                lxLed_Mtag.Text = "0";
                lxLed_Mtime.Text = "0";
                dataGridView4.Rows.Clear();
                btStartMactive.BackColor = Color.Indigo;
                fIsInventoryScan = false;
                btStartMactive.Text = ResourceCulture.GetString("btn_inventory_stop");
            }
        }

        private void GetRealtiemeData()
        {
            byte[] ScanModeData = new byte[40960];
            int nLen, NumLen;
            string temp1 = "";
            string RSSI = "";
            string AntStr = "";
            string lenstr = "";
            string EPCStr = "";
            int ValidDatalength;
            string temp;
            ValidDatalength = 0;
            DataGridViewRow rows = new DataGridViewRow();
            int xtime = System.Environment.TickCount;
            fCmdRet = RWDev.ReadActiveModeData(ScanModeData, ref ValidDatalength, frmcomportindex);
            if (fCmdRet == 0)
            {
                try
                {
                    byte[] daw = new byte[ValidDatalength];
                    Array.Copy(ScanModeData, 0, daw, 0, ValidDatalength);
                    temp = ByteArrayToHexString(daw);
                    fInventory_EPC_List = fInventory_EPC_List + temp;//把字符串存进列表
                    nLen = fInventory_EPC_List.Length;
                    while (fInventory_EPC_List.Length > 18)
                    {
                        string FlagStr = Convert.ToString(fComAdr, 16).PadLeft(2, '0') + "EE00";//查找头位置标志字符串
                        int nindex = fInventory_EPC_List.IndexOf(FlagStr);
                        if (nindex > 1)
                            fInventory_EPC_List = fInventory_EPC_List.Substring(nindex - 2);
                        else
                        {
                            fInventory_EPC_List = fInventory_EPC_List.Substring(2);
                            continue;
                        }
                        NumLen = Convert.ToInt32(fInventory_EPC_List.Substring(0, 2), 16) * 2 + 2;//取第一个帧的长度
                        if (fInventory_EPC_List.Length < NumLen)
                        {
                            break;
                        }
                        temp1 = fInventory_EPC_List.Substring(0, NumLen);
                        fInventory_EPC_List = fInventory_EPC_List.Substring(NumLen);
                        if (!RWDev.CheckCRC(temp1)) continue;
                        if (ReadTypes == "27" || ReadTypes == "65")
                            AntStr = Convert.ToInt32(temp1.Substring(8, 2), 16) + 1 + "";
                        else
                            AntStr = Convert.ToString(Convert.ToInt32(temp1.Substring(8, 2), 16), 2).PadLeft(4, '0');
                        lenstr = Convert.ToString(Convert.ToInt32(temp1.Substring(10, 2), 16), 10);
                        EPCStr = temp1.Substring(12, temp1.Length - 18);
                        RSSI = temp1.Substring(temp1.Length - 6, 2);
                        bool isonlistview = false;
                        for (int i = 0; i < dataGridView4.RowCount; i++)
                        {
                            if ((dataGridView4.Rows[i].Cells[1].Value != null) && (EPCStr == dataGridView4.Rows[i].Cells[1].Value.ToString()))
                            {
                                rows = dataGridView4.Rows[i];
                                rows.Cells[3].Value = AntStr;
                                rows.Cells[4].Value = RSSI;
                                isonlistview = true;
                                break;
                            }
                        }
                        if (!isonlistview)
                        {
                            string[] arr = new string[6];
                            arr[0] = (dataGridView4.RowCount + 1).ToString();
                            arr[1] = EPCStr;
                            arr[2] = lenstr;
                            arr[3] = AntStr;
                            arr[4] = RSSI;
                            dataGridView4.Rows.Insert(dataGridView4.RowCount, arr);
                        }
                        lxLed_Mtime.Text = (System.Environment.TickCount - total_time).ToString();
                    }
                }
                catch (System.Exception ex)
                {
                    ex.ToString();
                }
            }
            lxLed_Mtag.Text = dataGridView4.RowCount.ToString();
        }
        private void timer_RealTime_Tick(object sender, EventArgs e)
        {
            if (fIsInventoryScan) return;
            fIsInventoryScan = true;
            GetRealtiemeData();
            fIsInventoryScan = false;
        }

        private void radioButton_band8_CheckedChanged(object sender, EventArgs e)
        {
            int i;
            ComboBox_dmaxfre.Items.Clear();
            ComboBox_dminfre.Items.Clear();
            cmbReturnLossFreq.Items.Clear();
            for (i = 0; i < 20; i++)
            {
                ComboBox_dminfre.Items.Add(Convert.ToString(840.125 + i * 0.25) + " MHz");
                ComboBox_dmaxfre.Items.Add(Convert.ToString(840.125 + i * 0.25) + " MHz");
                cmbReturnLossFreq.Items.Add(Convert.ToString(840.125 + i * 0.25));
            }
            ComboBox_dmaxfre.SelectedIndex = 19;
            ComboBox_dminfre.SelectedIndex = 0;
            cmbReturnLossFreq.SelectedIndex = 10;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            byte WritePower = 0;
            WritePower = (byte)(com_wpower.SelectedIndex);
            if (rb_wp1.Checked)
            {
                ;// WritePower = WritePower;
            }
            else
            {
                WritePower = Convert.ToByte(WritePower | 0x80);
            }
            fCmdRet = RWDev.WriteRfPower(ref fComAdr, WritePower, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte WritePower = 0;
            fCmdRet = RWDev.ReadRfPower(ref fComAdr, ref WritePower, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                if ((WritePower & 0x80) == 0)
                {
                    rb_wp1.Checked = true;
                    com_wpower.SelectedIndex = Convert.ToInt32(WritePower);
                }
                else
                {
                    com_wpower.SelectedIndex = Convert.ToInt32(WritePower & 0x3F);
                    rb_wp2.Checked = true;
                }
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void bt_Setretry_Click(object sender, EventArgs e)
        {
            byte RetryTime = 0;
            RetryTime = (byte)(com_retrytimes.SelectedIndex | 0x80);
            fCmdRet = RWDev.RetryTimes(ref fComAdr, ref RetryTime, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void bt_Getretry_Click(object sender, EventArgs e)
        {
            byte Times = 0;
            fCmdRet = RWDev.RetryTimes(ref fComAdr, ref Times, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                com_retrytimes.SelectedIndex = Convert.ToInt32(Times);
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void rb_epc_CheckedChanged(object sender, EventArgs e)
        {
            gbp_MixRead.Enabled = false;
            com_S.Items.Clear();
            com_S.Items.Add("0");
            com_S.Items.Add("1");
            com_S.Items.Add("2");
            com_S.Items.Add("3");
            com_S.Items.Add("Auto-1");
            if (ModeType == 2)
            {
                com_S.Items.Add("Auto-2");
                com_S.Items.Add("Auto-3");
                com_S.SelectedIndex = 6;
            }
            else
            {
                com_S.SelectedIndex = 4;
            }
           
        }

        private void rb_mix_Click(object sender, EventArgs e)
        {

        }

        private void rb_mix_CheckedChanged(object sender, EventArgs e)
        {
            gbp_MixRead.Enabled = true;
            com_S.Items.Clear();
            com_S.Items.Add("0");
            com_S.Items.Add("1");
            com_S.Items.Add("2");
            com_S.Items.Add("3");
            com_S.SelectedIndex = 0;
            com_MixMem.Enabled = true;
            text_readpsd.Enabled = true;
            gbp_MixRead.Text = ResourceCulture.GetString("hint_group_mix"); 
        }

        private void rb_tid_CheckedChanged(object sender, EventArgs e)
        {
            gbp_MixRead.Enabled = true;
            com_S.Items.Clear();
            com_S.Items.Add("0");
            com_S.Items.Add("1");
            com_S.Items.Add("2");
            com_S.Items.Add("3");
            com_S.SelectedIndex = 0;
            com_MixMem.Enabled = false;
            text_readpsd.Enabled = false;
            gbp_MixRead.Text = ResourceCulture.GetString("hint_group_tid"); 
        }

        private void rb_fastid_CheckedChanged(object sender, EventArgs e)
        {
            gbp_MixRead.Enabled = false;
            com_S.Items.Clear();
            com_S.Items.Add("0");
            com_S.Items.Add("1");
            com_S.Items.Add("2");
            com_S.Items.Add("3");
            com_S.Items.Add("Auto-1");
            if (ModeType == 2)
            {
                com_S.Items.Add("Auto-2");
                com_S.Items.Add("Auto-3");
                com_S.SelectedIndex = 6;
            }
            else
            {
                com_S.SelectedIndex = 4;
            }
        }

        private void btnGetReaderTemperature_Click(object sender, EventArgs e)
        {

            byte PlusMinus = 0;
            byte Temperature = 0;
            string temp = "";
            txtReaderTemperature.Text = "";
            fCmdRet = RWDev.GetReaderTemperature(ref fComAdr, ref PlusMinus, ref Temperature, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                if (PlusMinus == 0)
                    temp = "-";
                temp += (Temperature.ToString() + "°C");
                txtReaderTemperature.Text =temp;
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btReturnLoss_Click(object sender, EventArgs e)
        {
            byte[] TestFreq = new byte[4];
            byte Ant = (byte)cbbAnt.SelectedIndex;
            byte ReturnLoss = 0;
            string temp = cmbReturnLossFreq.Text;

            float freq = Convert.ToSingle(Convert.ToSingle(temp) * 1000);
            int freq0 = Convert.ToInt32(freq);
            temp = Convert.ToString(freq0, 16).PadLeft(8, '0');
            TestFreq = HexStringToByteArray(temp);
            textReturnLoss.Text = "";
            fCmdRet = RWDev.MeasureReturnLoss(ref fComAdr, TestFreq, Ant, ref ReturnLoss, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                textReturnLoss.Text = ReturnLoss.ToString()+"dB";
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void radioButton_band12_CheckedChanged(object sender, EventArgs e)
        {
            int i;
            ComboBox_dmaxfre.Items.Clear();
            ComboBox_dminfre.Items.Clear();
            cmbReturnLossFreq.Items.Clear();
            for (i = 0; i < 53; i++)
            {
                ComboBox_dminfre.Items.Add(Convert.ToString(902 + i * 0.5) + " MHz");
                ComboBox_dmaxfre.Items.Add(Convert.ToString(902 + i * 0.5) + " MHz");
                cmbReturnLossFreq.Items.Add(Convert.ToString(902 + i * 0.5));
            }
            ComboBox_dmaxfre.SelectedIndex = 52;
            ComboBox_dminfre.SelectedIndex = 0;
            cmbReturnLossFreq.SelectedIndex = 26;
        }

        private void radioButton_band0_CheckedChanged(object sender, EventArgs e)
        {
            int i;
            ComboBox_dmaxfre.Items.Clear();
            ComboBox_dminfre.Items.Clear();
            cmbReturnLossFreq.Items.Clear();
            for (i = 0; i < 61; i++)
            {
                ComboBox_dminfre.Items.Add(Convert.ToString(840 + i * 2) + " MHz");
                ComboBox_dmaxfre.Items.Add(Convert.ToString(840 + i * 2) + " MHz");
                cmbReturnLossFreq.Items.Add(Convert.ToString(840 + i * 2));
            }
            ComboBox_dmaxfre.SelectedIndex = 60;
            ComboBox_dminfre.SelectedIndex = 0;
            cmbReturnLossFreq.SelectedIndex = 30;
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            byte Profile = 0;
            if (ModeType == 0)
            {
                if (comboBox4.SelectedIndex == 0) Profile = 0x90;
                if (comboBox4.SelectedIndex == 1) Profile = 0x91;
                if (comboBox4.SelectedIndex == 2) Profile = 0x92;
                if (comboBox4.SelectedIndex == 3) Profile = 0x93;
                if (comboBox4.SelectedIndex == 4) Profile = 0x94;
            }
            else if (ModeType == 1)
            {
                if (comboBox4.SelectedIndex == 0) Profile = 0x80;
                if (comboBox4.SelectedIndex == 1) Profile = 0x81;
                if (comboBox4.SelectedIndex == 2) Profile = 0x82;
                if (comboBox4.SelectedIndex == 3) Profile = 0x83;
            }
            else if (ModeType == 2)
            {
                if (comboBox4.SelectedIndex == 0) Profile = 11;
                if (comboBox4.SelectedIndex == 1) Profile = 1;
                if (comboBox4.SelectedIndex == 2) Profile = 15;
                if (comboBox4.SelectedIndex == 3) Profile = 12;
                if (comboBox4.SelectedIndex == 4) Profile = 3;
                if (comboBox4.SelectedIndex == 5) Profile = 5;
                if (comboBox4.SelectedIndex == 6) Profile = 7;
                if (comboBox4.SelectedIndex == 7) Profile = 13;
                if (comboBox4.SelectedIndex == 8) Profile = 50;
                if (comboBox4.SelectedIndex == 9) Profile = 51;
                if (comboBox4.SelectedIndex == 10) Profile = 52;
                if (comboBox4.SelectedIndex == 11) Profile = 53;
                Profile |= 0x80;
            }

            fCmdRet = RWDev.SetProfile(ref fComAdr, ref Profile, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
                RF_Profile = Profile;
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            byte Profile = 0;
            fCmdRet = RWDev.SetProfile(ref fComAdr, ref Profile, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                if (ModeType == 0)
                {
                    if (Profile == 0x10) comboBox4.SelectedIndex = 0;
                    if (Profile == 0x11) comboBox4.SelectedIndex = 1;
                    if (Profile == 0x12) comboBox4.SelectedIndex = 2;
                    if (Profile == 0x13) comboBox4.SelectedIndex = 3;
                    if (Profile == 0x14) comboBox4.SelectedIndex = 4;
                }
                else if (ModeType == 1)
                {
                    if (Profile == 0x00) comboBox4.SelectedIndex = 0;
                    if (Profile == 0x01) comboBox4.SelectedIndex = 1;
                    if (Profile == 0x02) comboBox4.SelectedIndex = 2;
                    if (Profile == 0x03) comboBox4.SelectedIndex = 3;
                }
                else if (ModeType == 2)
                {
                    if (Profile == 11) comboBox4.SelectedIndex = 0;
                    if (Profile == 1) comboBox4.SelectedIndex = 1;
                    if (Profile == 15) comboBox4.SelectedIndex = 2;
                    if (Profile == 12) comboBox4.SelectedIndex = 3;
                    if (Profile == 3) comboBox4.SelectedIndex = 4;
                    if (Profile == 5) comboBox4.SelectedIndex = 5;
                    if (Profile == 7) comboBox4.SelectedIndex = 6;
                    if (Profile == 13) comboBox4.SelectedIndex = 7;
                    if (Profile == 50) comboBox4.SelectedIndex = 8;
                    if (Profile == 51) comboBox4.SelectedIndex = 9;
                    if (Profile == 52) comboBox4.SelectedIndex = 10;
                    if (Profile == 53) comboBox4.SelectedIndex = 11;
                    RF_Profile = Profile;
                }
                else if (ModeType == 4)
                {
                    if (Profile == 0x20) comboBox4.SelectedIndex = 0;
                    if (Profile == 0x21) comboBox4.SelectedIndex = 1;
                    if (Profile == 0x22) comboBox4.SelectedIndex = 2;
                    if (Profile == 0x23) comboBox4.SelectedIndex = 3;
                    if (Profile == 0x24) comboBox4.SelectedIndex = 4;
                    if (Profile == 0x25) comboBox4.SelectedIndex = 5;
                    if (Profile == 0x26) comboBox4.SelectedIndex = 6;
                    if (Profile == 0x27) comboBox4.SelectedIndex = 7;
                    if (Profile == 0x28) comboBox4.SelectedIndex = 8;
                }
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }



        private void ChangeShow(int mtype)
        {
            com_MixMem.Items.Clear();
            if (mtype == 0)
            {
                com_MixMem.Items.Add("Reserve");
                com_MixMem.Items.Add("EPC");
                com_MixMem.Items.Add("TID");
                com_MixMem.Items.Add("User");
                com_MixMem.SelectedIndex = 2;
                R_EPC.Text = "EPC";
                R_TID.Text = "TID";
                P_EPC.Text = "EPC";
                P_TID.Text = "TID";
                rb_epc.Text = "EPC";
                rb_tid.Text = "TID";
                C_EPC.Text = "EPC";
                C_TID.Text = "TID";
            }
            else
            {
                com_MixMem.Items.Add("Reserve");
                com_MixMem.Items.Add("MUII");
                com_MixMem.Items.Add("CID");
                com_MixMem.Items.Add("User");
                com_MixMem.SelectedIndex = 2;
                R_EPC.Text = "MUII";
                R_TID.Text = "CID";
                P_EPC.Text = "MUII";
                P_TID.Text = "CID";
                rb_epc.Text = "MUII";
                rb_tid.Text = "CID";
                C_EPC.Text = "MUII";
                C_TID.Text = "CID";
            }
        }

        private void rbcra_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox15_CheckedChanged(object sender, EventArgs e)
        {

        }

      

        private byte[] NumtoBytes(int num)
        {
            byte[] data = new byte[2];
            data[0] = (byte)(num >> 8);
            data[1] = (byte)(num & 0xFF);
            return data;
        }


       
        private void Maintab_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if ((mythread != null) || (ledthread != null))
            {
                e.Cancel = true;
                MessageBox.Show(ResourceCulture.GetString("msg_close_thread"));
                return;
            }
            if (tabControl2.SelectedTab != tabPage17)
            {
                dataGridView6.Columns.Clear();
                dataGridView6.DataSource = null;
                lxLedControl10.Text = "0";
            }
        }

        private void btSetRfPower_Click(object sender, EventArgs e)
        {
            byte[] powerDbm = new byte[16];
            if ((txtPower1.Text.Length == 0) || (Convert.ToByte(txtPower1.Text, 10) > 33))
            {
                return;
            }
            if ((txtPower2.Text.Length == 0) || (Convert.ToByte(txtPower2.Text, 10) > 33))
            {
                return;
            }
            
            powerDbm[0] = Convert.ToByte(txtPower1.Text, 10);
            powerDbm[1] = Convert.ToByte(txtPower2.Text, 10);
           
            if (!checkBox3.Checked)
            {
                powerDbm[0] |= 0x80;
                powerDbm[1] |= 0x80;
            }
            fCmdRet = RWDev.SetAntennaPower(ref fComAdr, powerDbm, 4, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_power_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_power_succeed");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btGetRfPower_Click(object sender, EventArgs e)
        {
            byte[] powerDbm = new byte[16];
            int length = 0;
            fCmdRet = RWDev.GetAntennaPower(ref fComAdr, powerDbm, ref length, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_power_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                switch (length)
                {
                    case 1:
                        txtPower1.Text = powerDbm[0].ToString();
                        break;
                    case 4:
                        txtPower1.Text = powerDbm[0].ToString();
                        txtPower2.Text = powerDbm[1].ToString();
                        break;
                }

                string strLog = ResourceCulture.GetString("log_get_power_succeed"); 
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
        }

        private void button4_Click(object sender, EventArgs e)
        {
          
        }

        private void button8_Click(object sender, EventArgs e)
        {
            byte opt = 1;
            if (checkBox6.Checked) opt = 0;
            byte cfgNo = 7;
            byte[] cfgData = new byte[256];
            int len = 3;
            cfgData[0] = (byte)com_queryInter.SelectedIndex;
            cfgData[1] = (byte)(cbb_dwell.SelectedIndex + 2);
            cfgData[2] = (byte)cbb_add.SelectedIndex;
            int fCmdRet = RWDev.SetCfgParameter(ref fComAdr, opt, cfgNo, cfgData, len, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_failed")+ GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            byte cfgNo = 7;
            byte[] cfgData = new byte[256];
            int len = 0;
            int fCmdRet = RWDev.GetCfgParameter(ref fComAdr, cfgNo, cfgData, ref len, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                if (len == 3)
                {
                    com_queryInter.SelectedIndex = cfgData[0];
                    cbb_dwell.SelectedIndex = cfgData[1] - 2;
                    cbb_add.SelectedIndex = cfgData[2];
                }
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            byte enFlag = 1;
            if (rb_enable.Checked) enFlag = 1;
            else
                enFlag = 0;
            byte cfgNo = 8;
            byte[] cfgData = new byte[256];
            int len = 1;
            cfgData[0] = (byte)enFlag;
            int fCmdRet = RWDev.SetCfgParameter(ref fComAdr, 0, cfgNo, cfgData, len, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            byte cfgNo = 8;
            byte[] cfgData = new byte[256];
            int len = 0;
            int fCmdRet = RWDev.GetCfgParameter(ref fComAdr, cfgNo, cfgData, ref len, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                if (len == 1)
                {
                    if (cfgData[0] == 1)
                    {
                        rb_enable.Checked = true;
                    }
                    else
                    {
                        rb_disable.Checked = true;
                    }
                }
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            ParamSetting mSet = new ParamSetting();
            mSet.ShowDialog();
        }


        public byte GetSession()
        {
            byte cfgNum = 0x09;
            byte[] data = new byte[256];
            int len = 0;
            int fCmdRet = RWDev.GetCfgParameter(ref fComAdr, cfgNum, data, ref len, frmcomportindex);
            if (fCmdRet == 0)
            {
                return data[1];
            }
            else
            {
                return 1;
            }
        }
       
        private void text_target_TextChanged(object sender, EventArgs e)
        {

        }

        private void button12_Click(object sender, EventArgs e)
        {
            if ((textBox2.Text == "") || (textBox1.Text == "") || (comboBox6.Text == "")) return;
            byte freSpace = 0;
            byte freNum = 0;
            byte[] freStart = new byte[3];
            byte opt = 0;
            if (!checkBox7.Checked) opt = 1;
            freSpace = Convert.ToByte(textBox2.Text, 10);
            freNum = (byte)(comboBox6.SelectedIndex + 1);
            int freq = Convert.ToInt32(textBox1.Text, 10);
            freStart[0] = (byte)(freq >> 16);
            freStart[1] = (byte)(freq >> 8);
            freStart[2] = (byte)(freq);
            int fCmdRet = RWDev.SetCustomRegion(ref fComAdr, opt, freSpace, freNum, freStart, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            byte freSpace = 0;
            byte freNum = 0;
            byte[] freStart = new byte[3];
            int fCmdRet = RWDev.GetCustomRegion(ref fComAdr, ref freSpace, ref freNum, freStart, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                textBox1.Text = (freStart[0] << 16) + (freStart[1] << 8) + (freStart[2]) + "";
                comboBox6.SelectedIndex = freNum - 1;
                textBox2.Text = freSpace + "";
                string strLog = ResourceCulture.GetString("log_get_success"); ;
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void button21_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            Application.DoEvents();
            string str = "";
            Information.IP = "";
            Information.usename = "";
            Information.dsname = "";
            Information.mac = "";
            Information.portnum = "";
            Information.tup = "";
            Information.rm = "";
            Information.cm = "";
            Information.ct = "";
            Information.fc = "";
            Information.dt = "";
            Information.br = "";
            Information.pr = "";
            Information.bb = "";
            Information.rc = "";
            Information.ml = "";
            Information.md = "";
            Information.di = "";
            Information.dp = "";
            Information.gi = "";
            Information.nm = "";
            byte[] data = new byte[1024];
            ListViewItem aListItem = new ListViewItem();
            try
            {

                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//初始化一个Scoket实习,采用UDP传输
                int ipindex = comboBox11.Text.IndexOf(":");
                string IPAddr = comboBox11.Text.Substring(0, ipindex);
                IPAddress IPLocal = IPAddress.Parse(IPAddr);
                sock.Bind(new IPEndPoint(IPLocal, 0));
                IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 65535);//初始化一个发送广播和指定端口的网络端口实例
                IPEndPoint iep1 = new IPEndPoint(IPAddress.Any, 65535);//初始化一个发送广播和指定端口的网络端口实例
                EndPoint ep = (EndPoint)iep;
                EndPoint ep1 = (EndPoint)iep1;
                sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);//设置该scoket实例的发送形式
                string request = "X";//初始化需要发送的数据
                byte[] buffer = Encoding.ASCII.GetBytes(request);
                sock.SendTo(buffer, iep);
                int errorCount = 0;
                for (int i = 0; i < 255; i++)
                {
                    byte[] buffer1 = new byte[1000];
                    sock.ReceiveTimeout = 50;
                    int m_count = 0;
                    try
                    {
                        m_count = sock.ReceiveFrom(buffer1, ref ep1);
                    }
                    catch (Exception ex)
                    {
                        ex.ToString();
                        if (errorCount >= 3) break;
                        errorCount++;
                    }
                    if (m_count > 0)
                    {
                        aListItem = listView1.Items.Add((listView1.Items.Count + 1).ToString());
                        aListItem.SubItems.Add("");
                        aListItem.SubItems.Add("");
                        aListItem.SubItems.Add("");
                        byte[] buffer2 = new byte[m_count];
                        Array.Copy(buffer1, buffer2, m_count);
                        string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                        if (fRecvIDPstring.Substring(0, 1) == "A")
                        {
                            int m = fRecvIDPstring.IndexOf('/');
                            Information.mac = fRecvIDPstring.Substring(1, m - 1);
                            Information.portnum = fRecvIDPstring.Substring(m + 1, 4);
                            m = fRecvIDPstring.IndexOf('*');
                            int n = fRecvIDPstring.Length - m - 8;
                            string IDPstring = fRecvIDPstring.Substring(m + 8, n);
                            Information.usename = IDPstring.Substring(0, IDPstring.IndexOf('/'));
                            Information.dsname = IDPstring.Substring(IDPstring.IndexOf('/') + 1, IDPstring.Length - IDPstring.IndexOf('/') - 1);
                            Information.IP = ep1.ToString().Substring(0, ep1.ToString().IndexOf(':'));
                            if (((Information.usename == "") && (Information.dsname == "")) || (Information.dsname == "/"))
                            {
                                str = "";
                            }
                            else
                            {
                                str = Information.usename + '/' + Information.dsname;
                            }
                            aListItem.SubItems[1].Text = Information.mac;
                            aListItem.SubItems[2].Text = Information.IP;
                            aListItem.SubItems[3].Text = str;
                        }
                    }
                }
                sock.Close();
            }
            catch (System.Exception ex)
            {
                ex.ToString();
                return;
            }
        }

        private void button23_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            Application.DoEvents();
            Information.IP = "";
            Information.usename = "";
            Information.dsname = "";
            Information.mac = "";
            Information.portnum = "";
            Information.tup = "";
            Information.rm = "";
            Information.cm = "";
            Information.ct = "";
            Information.fc = "";
            Information.dt = "";
            Information.br = "";
            Information.pr = "";
            Information.bb = "";
            Information.rc = "";
            Information.ml = "";
            Information.md = "";
            Information.di = "";
            Information.dp = "";
            Information.gi = "";
            Information.nm = "";
            locateForm loginform = new locateForm();
            DialogResult result = loginform.ShowDialog();
            if (result == DialogResult.OK)
            {
                try
                {
                    string IPAddr = loginform.IP1 + "." + loginform.IP2 + "." + loginform.IP3 + "." + loginform.IP4;
                    listView1.Items.Clear();
                    string str = "";
                    byte[] data = new byte[1024];
                    ListViewItem aListItem = new ListViewItem();
                    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//初始化一个Scoket实习,采用UDP传输
                    int ipindex = comboBox11.Text.IndexOf(":");
                    string IPAddr2 = comboBox11.Text.Substring(0, ipindex);
                    IPAddress IPLocal = IPAddress.Parse(IPAddr2);
                    sock.Bind(new IPEndPoint(IPLocal, 0));
                    IPEndPoint iep = new IPEndPoint(IPAddress.Parse(IPAddr), 65535);//初始化一个发送广播和指定端口的网络端口实例
                    EndPoint ep = (EndPoint)iep;
                    sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);//设置该scoket实例的发送形式
                    string request = "X";//初始化需要发送的数据
                    byte[] buffer = Encoding.ASCII.GetBytes(request);
                    sock.SendTo(buffer, iep);
                    for (int i = 0; i < 3; i++)
                    {
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        iep = new IPEndPoint(IPAddress.Parse(IPAddr), 65535);
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            aListItem = listView1.Items.Add((listView1.Items.Count + 1).ToString());
                            aListItem.SubItems.Add("");
                            aListItem.SubItems.Add("");
                            aListItem.SubItems.Add("");
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('/');
                                Information.mac = fRecvIDPstring.Substring(1, m - 1);
                                Information.portnum = fRecvIDPstring.Substring(m + 1, 4);
                                m = fRecvIDPstring.IndexOf('*');
                                int n = fRecvIDPstring.Length - m - 8;
                                string IDPstring = fRecvIDPstring.Substring(m + 8, n);
                                Information.usename = IDPstring.Substring(0, IDPstring.IndexOf('/'));
                                Information.dsname = IDPstring.Substring(IDPstring.IndexOf('/') + 1, IDPstring.Length - IDPstring.IndexOf('/') - 1);
                                Information.IP = ep.ToString().Substring(0, ep.ToString().IndexOf(':'));
                                if (((Information.usename == "") && (Information.dsname == "")) || (Information.dsname == "/"))
                                {
                                    str = "";
                                }
                                else
                                {
                                    str = Information.usename + '/' + Information.dsname;
                                }
                                if (IPAddr == Information.IP)
                                {
                                    aListItem.SubItems[1].Text = Information.mac;
                                    aListItem.SubItems[2].Text = Information.IP;
                                    aListItem.SubItems[3].Text = str;
                                }
                            }
                            break;
                        }

                    }
                    sock.Close();
                }
                catch (System.Exception ex)
                {
                    ex.ToString();
                }
            }
            loginform.Dispose();
        }

        private void button24_Click(object sender, EventArgs e)
        {
            int i = 0;
            string IPaddr = "";
            try
            {
                if (listView1.SelectedIndices.Count > 0
                    && listView1.SelectedIndices[0] != -1)
                {
                    IPaddr = listView1.SelectedItems[0].SubItems[2].Text;
                    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//初始化一个Scoket实习,采用UDP传输
                    int ipindex = comboBox11.Text.IndexOf(":");
                    string IPAddr = comboBox11.Text.Substring(0, ipindex);
                    IPAddress IPLocal = IPAddress.Parse(IPAddr);
                    sock.Bind(new IPEndPoint(IPLocal, 0));
                    IPEndPoint iep = new IPEndPoint(IPAddress.Parse(IPaddr), 65535);//初始化一个发送广播和指定端口的网络端口实例
                    EndPoint ep = (EndPoint)iep;
                    sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);//设置该scoket实例的发送形式
                    string request = "X";//初始化需要发送的数据
                    byte[] buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {

                        sock.SendTo(buffer, iep);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('/');
                                Information.mac = fRecvIDPstring.Substring(1, m - 1);
                                Information.portnum = fRecvIDPstring.Substring(m + 1, 4);
                                m = fRecvIDPstring.IndexOf('*');
                                int n = fRecvIDPstring.Length - m - 8;
                                string IDPstring = fRecvIDPstring.Substring(m + 8, n);
                                Information.usename = IDPstring.Substring(0, IDPstring.IndexOf('/'));
                                Information.dsname = IDPstring.Substring(IDPstring.IndexOf('/') + 1, IDPstring.Length - IDPstring.IndexOf('/') - 1);
                                Information.IP = ep.ToString().Substring(0, ep.ToString().IndexOf(':'));
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "W" + Information.mac;//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(100);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "L";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(50);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GON|1";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 1) == "1")
                                {
                                    Information.usename = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GDN|2";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 1) == "2")
                                {
                                    Information.dsname = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GFE|3";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 1) == "3")
                                {
                                    Information.mac = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GIP|4";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 1) == "4")
                                {
                                    Information.IP = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GPN|5";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 1) == "5")
                                {
                                    Information.portnum = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GTP|6";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 1) == "6")
                                {
                                    Information.tup = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GRM|7";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 1) == "7")
                                {
                                    Information.rm = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GCM|8";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 1) == "8")
                                {
                                    Information.cm = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GCT|9";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 1) == "9")
                                {
                                    Information.ct = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GFC|10";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "10")
                                {
                                    Information.fc = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GDT|11";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "11")
                                {
                                    Information.dt = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GBR|12";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "12")
                                {
                                    Information.br = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GPR|13";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "13")
                                {
                                    Information.pr = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GBB|14";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "14")
                                {
                                    Information.bb = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GRC|15";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "15")
                                {
                                    Information.rc = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GML|16";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "16")
                                {
                                    Information.ml = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GMD|17";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "17")
                                {
                                    Information.md = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GDI|18";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "18")
                                {
                                    Information.di = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GDP|19";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "19")
                                {
                                    Information.dp = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GGI|20";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "20")
                                {
                                    Information.gi = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    i = 0;
                    request = "GNM|21";//初始化需要发送的数据
                    buffer = Encoding.ASCII.GetBytes(request);
                    while (i < 3)
                    {
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        byte[] buffer1 = new byte[1000];
                        sock.ReceiveTimeout = 50;
                        int m_count = sock.ReceiveFrom(buffer1, ref ep);
                        if (m_count > 0)
                        {
                            byte[] buffer2 = new byte[m_count];
                            Array.Copy(buffer1, buffer2, m_count);
                            string fRecvIDPstring = Encoding.ASCII.GetString(buffer2);
                            if (fRecvIDPstring.Substring(0, 1) == "A")
                            {
                                int m = fRecvIDPstring.IndexOf('|');
                                if (fRecvIDPstring.Substring(m + 1, 2) == "21")
                                {
                                    Information.nm = fRecvIDPstring.Substring(1, m - 1);
                                }
                                i = 3;
                                break;
                            }
                        }
                        i = i + 1;
                    }

                    if ((Information.nm == "") || (Information.mac == "") || (Information.IP == "") || (Information.portnum == "") ||
                        (Information.br == "") || (Information.bb == "") || (Information.dt == "") || (Information.rm == "") ||
                        (Information.tup == "") || (Information.pr == "") || (Information.fc == "") || (Information.di == "") || (Information.dp == "") || (Information.gi == ""))
                    {
                        return;
                    }
                    fSetdlg fsetdlg = new fSetdlg();
                    fsetdlg._IP(Information.IP);
                    fsetdlg._bb(Information.bb);
                    fsetdlg._br(Information.br);
                    fsetdlg._di(Information.di);
                    fsetdlg._dp(Information.dp);
                    fsetdlg._dsname(Information.dsname);
                    fsetdlg._dt(Information.dt);
                    fsetdlg._fc(Information.fc);
                    fsetdlg._gi(Information.gi);
                    fsetdlg._MAC(Information.mac);
                    fsetdlg._nm(Information.nm);
                    fsetdlg._portnum(Information.portnum);
                    fsetdlg._pr(Information.pr);
                    fsetdlg._rm(Information.rm);
                    fsetdlg._tup(Information.tup);
                    fsetdlg._usename(Information.usename);
                    DialogResult result = fsetdlg.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        request = "L";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(50);

                        request = "SON" + Information.usename + "|18";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SDN" + Information.dsname + "|19";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "STP" + Information.tup + "|20";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SPN" + Information.portnum + "|21";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SRM" + Information.rm + "|22";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SFC" + Information.fc + "|23";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SDT" + Information.dt + "|24";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SBR" + Information.br + "|25";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SPR" + Information.pr + "|26";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SBB" + Information.bb + "|27";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SRC" + Information.rc + "|28";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SCM" + Information.cm + "|29";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SCT" + Information.ct + "|30";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SML" + Information.ml + "|31";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SMD" + Information.md + "|32";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SDI" + Information.di + "|33";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SDP" + Information.dp + "|34";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SGI" + Information.gi + "|35";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SNM" + Information.nm + "|36";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SIP" + Information.IP + "|37";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "E";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(500);

                        iep = new IPEndPoint(IPAddress.Broadcast, 65535);//初始化一个发送广播和指定端口的网络端口实例
                        sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);

                        request = "W" + Information.mac;//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(100);

                        request = "L";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(50);

                        request = "SON" + Information.usename + "|18";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SDN" + Information.dsname + "|19";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "STP" + Information.tup + "|20";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SPN" + Information.portnum + "|21";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SRM" + Information.rm + "|22";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SFC" + Information.fc + "|23";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SDT" + Information.dt + "|24";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SBR" + Information.br + "|25";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SPR" + Information.pr + "|26";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SBB" + Information.bb + "|27";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SRC" + Information.rc + "|28";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SCM" + Information.cm + "|29";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SCT" + Information.ct + "|30";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SML" + Information.ml + "|31";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SMD" + Information.md + "|32";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SDI" + Information.di + "|33";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SDP" + Information.dp + "|34";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SGI" + Information.gi + "|35";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SNM" + Information.nm + "|36";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "SIP" + Information.IP + "|33";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);

                        request = "E";//初始化需要发送的数据
                        buffer = Encoding.ASCII.GetBytes(request);
                        sock.SendTo(buffer, iep);
                        Thread.Sleep(10);
                        listView1.Items.Clear();
                    }
                    fsetdlg.Dispose();
                    sock.Close();
                }
                else
                {
                    MessageBox.Show(ResourceCulture.GetString("log_not_select_device"), ResourceCulture.GetString("hint_info"));
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }


        List<string> ledmlist = new List<string>();
        int ledTagType = 0;
        private volatile bool StopLedThread = false;
        private Thread ledthread = null;
        int workType = 0;
        bool isPhase = false;
        byte delayTime = 0;
        byte intervalTime = 0;
        byte rf_switch = 0;
        private void button13_Click(object sender, EventArgs e)
        {
            if (button13.Text == ResourceCulture.GetString("btn_inventory_start"))
            {
                if (ledthread == null)
                {
                    isPhase = checkBox8.Checked;

                    if (chk_rf.Checked)
                        rf_switch = 1;
                    else
                        rf_switch = 0;
                    delayTime = (byte)cbb_rf_delaytime.SelectedIndex;
                    Qvalue = (byte)cbb_led_q.SelectedIndex;
                    Session = (byte)cbb_led_s.SelectedIndex;
                    Target = (byte)cbb_led_t.SelectedIndex;
                    targettimes = Convert.ToByte(txt_led_count.Text, 10);
                    intervalTime = (byte)cbb_cmd_interval.SelectedIndex;
                    Array.Clear(antlist, 0, 16);
                    int SelectAntenna = 0;
                    if (led_ant1.Checked)
                    {
                        antlist[0] = 1;
                        InAnt = 0x80;
                        SelectAntenna |= 0x0001;
                    }
                    if (led_ant2.Checked)
                    {
                        antlist[1] = 1;
                        InAnt = 0x81;
                        SelectAntenna |= 0x0002;
                    }
                    if (led_ant3.Checked)
                    {
                        antlist[2] = 1;
                        InAnt = 0x82;
                        SelectAntenna |= 0x0004;
                    }
                    if (led_ant4.Checked)
                    {
                        antlist[3] = 1;
                        InAnt = 0x83;
                        SelectAntenna |= 0x0008;
                    }


                    if (led_ant5.Checked)
                    {
                        antlist[4] = 1;
                        InAnt = 0x84;
                        SelectAntenna |= 0x0010;
                    }

                    if (led_ant6.Checked)
                    {
                        antlist[5] = 1;
                        InAnt = 0x85;
                        SelectAntenna |= 0x0020;
                    }

                    if (led_ant7.Checked)
                    {
                        antlist[6] = 1;
                        InAnt = 0x86;
                        SelectAntenna |= 0x0040;
                    }

                    if (led_ant8.Checked)
                    {
                        antlist[7] = 1;
                        InAnt = 0x87;
                        SelectAntenna |= 0x0080;
                    }

                    if (led_ant9.Checked)
                    {
                        antlist[8] = 1;
                        InAnt = 0x88;
                        SelectAntenna |= 0x0100;
                    }
                    if (led_ant10.Checked)
                    {
                        antlist[9] = 1;
                        InAnt = 0x89;
                        SelectAntenna |= 0x0200;
                    }
                    if (led_ant11.Checked)
                    {
                        antlist[10] = 1;
                        InAnt = 0x8A;
                        SelectAntenna |= 0x0400;
                    }
                    if (led_ant12.Checked)
                    {
                        antlist[11] = 1;
                        InAnt = 0x8B;
                        SelectAntenna |= 0x0800;
                    }


                    if (led_ant13.Checked)
                    {
                        antlist[12] = 1;
                        InAnt = 0x8C;
                        SelectAntenna |= 0x1000;
                    }

                    if (led_ant14.Checked)
                    {
                        antlist[13] = 1;
                        InAnt = 0x8D;
                        SelectAntenna |= 0x2000;
                    }

                    if (led_ant15.Checked)
                    {
                        antlist[14] = 1;
                        InAnt = 0x8E;
                        SelectAntenna |= 0x4000;
                    }

                    if (led_ant16.Checked)
                    {
                        antlist[15] = 1;
                        InAnt = 0x8F;
                        SelectAntenna |= 0x8000;
                    }

                    if (radioButton1.Checked)
                    {
                        epclist.Clear();
                        dataGridView6.Columns.Clear();
                        dataGridView6.DataSource = null;
                        workType = 0;
                    }
                    else
                    {
                        if (dataGridView6.DataSource == null || dataGridView6.Rows.Count == 0) return;
                        ledmlist.Clear();
                        workType = 1;
                        for (int m = 0; m < dataGridView6.Rows.Count; m++)
                        {
                            if (dataGridView6.Rows[m].Cells[0].Value != null && dataGridView6.Rows[m].Cells[0].Value.ToString().ToLower() == "true")
                            {
                                string epc = dataGridView6.Rows[m].Cells[1].Value.ToString();
                                ledmlist.Add(epc);
                            }
                        }
                        if (ledmlist.Count == 0)
                        {
                            MessageBox.Show(ResourceCulture.GetString("hint_select_tag"));
                            return;
                        }
                    }

                    button13.Text = ResourceCulture.GetString("btn_inventory_stop");

                    ledTagType = comboBox1.SelectedIndex;

                    curList.Clear();
                    timer_answer.Enabled = true;
                    reflasg = false;
                    StopLedThread = false;
                    ledthread = new Thread(new ThreadStart(startLedTag));
                    ledthread.IsBackground = true;
                    ledthread.Start();
                }
            }
            else
            {
                StopLedThread = true;
            }
        }

        byte MaskFlag = 0;
        private void startLedTag()
        {

            byte opt = 1;
            byte cfgNo = 7;
            byte[] cfgData = new byte[256];
            int len = 3;
            cfgData[0] = 0;
            cfgData[1] = 50;
            cfgData[2] = 0;
            int fCmdRet = RWDev.SetCfgParameter(ref fComAdr, opt, cfgNo, cfgData, len, frmcomportindex);
            //配置载波延时
            cfgNo = 0x15;
            len = 1;
            cfgData[0] = delayTime;
            fCmdRet = RWDev.SetCfgParameter(ref fComAdr, opt, cfgNo, cfgData, len, frmcomportindex);

            ////配置发命令前是否关载波
            cfgNo = 0x16;
            len = 1;
            cfgData[0] = rf_switch;
            fCmdRet = RWDev.SetCfgParameter(ref fComAdr, opt, cfgNo, cfgData, len, frmcomportindex);

            AA_times = 0;

            while (!StopLedThread)
            {
                if (workType == 0)//盘存标签
                {
                    MaskFlag = 0;
                    byte MaskMem = 2;
                    byte[] MaskAdr = new byte[2];
                    MaskAdr[0] = MaskAdr[1] = 0;
                    byte MaskLen = 24;
                    byte[] MaskData = new byte[20];
                    for (int m = 0; m < 16;m++ )
                    {
                        if(antlist[m]==1)
                        {
                            byte antenna = (byte)(m | 0x80);
                            scanled(MaskMem, MaskAdr, MaskLen, MaskData,antenna);
                            
                            if (StopLedThread) break;
                        }
                    }
                    
                }
                else
                {
                    MaskFlag = 1;
                    for (int m = 0; m < ledmlist.Count; m++)
                    {
                        string temp = ledmlist[m];
                        byte[] Password = new byte[4];
                        Password[0] = Password[1] = Password[2] = Password[3] = 0;
                        byte MaskMem = 1;
                        byte[] MaskAdr = new byte[2];
                        MaskAdr[0] = 0x00;
                        MaskAdr[1] = 0x20;
                        byte MaskLen = (byte)(temp.Length * 4);
                        byte[] MaskData = new byte[100];
                        MaskData = HexStringToByteArray(temp);
                        //scanled(MaskMem, MaskAdr, MaskLen, MaskData);
                        for (int p = 0; p < 16;p++)
                        {
                            if (antlist[p] == 1)
                            {
                                byte antenna = (byte)(p | 0x80);
                                scanled(MaskMem, MaskAdr, MaskLen, MaskData, antenna);
                                if (StopLedThread) break;
                            }
                        }
                        if (StopLedThread) break;
                    }
                }
            }

            this.Invoke((EventHandler)delegate
            {
                button13.Text = ResourceCulture.GetString("btn_inventory_start");
                ledthread = null;
            });
        }


        void scanled(byte MaskMem, byte[] MaskAdr, byte MaskLen, byte[] MaskData,byte curantenna)
        {
            byte Ant = 0;
            int TagNum = 0;
            int Totallen = 0;
            byte[] EPC = new byte[50000];
            
            byte ReadMem = 0;
            byte ReadLen = 1;
            byte[] ReadAdr = new byte[2];
            byte[] Psd = new byte[4];

            int cbtime = System.Environment.TickCount;

            CardNum = 0;
            NewCardNum = 0;

            FastFlag = 1;
            if (isPhase) Qvalue |= 0x10;
            if (ledTagType == 0)
            {
                ReadMem = 0;
                ReadLen = 1;
                ReadAdr[0] = 0;
                ReadAdr[1] = 4;
            }
            else if (ledTagType == 1)
            {
                ReadMem = 3;
                ReadLen = 1;
                ReadAdr[0] = 0;
                ReadAdr[1] = 112;
            }
            else if (ledTagType == 2)
            {
                ReadMem = 0;
                ReadLen = 1;
                ReadAdr[0] = 0;
                ReadAdr[1] = 5;
            }
            else
            {
                ReadMem = 0;
                ReadLen = 1;
                ReadAdr[0] = 0;
                ReadAdr[1] = 6;
            }


            Psd[0] = Psd[1] = Psd[2] = Psd[3] = 0;

            fCmdRet = RWDev.InventoryMix_G2(ref fComAdr, Qvalue, Session, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, ReadMem, ReadAdr, ReadLen, Psd, Target, curantenna, Scantime, FastFlag, EPC, ref Ant, ref Totallen, ref TagNum, frmcomportindex);
            int cmdTime = System.Environment.TickCount - cbtime;//命令时间
            if ((fCmdRet != 0x01) && (fCmdRet != 0x02) && (fCmdRet != 0xF8) && (fCmdRet != 0xF9) && (fCmdRet != 0xEE) && (fCmdRet != 0xFF))
            {
                if (rb_tcp.Checked)
                {
                    if ((frmcomportindex > 0) && (frmcomportindex < 256))
                    {
                        fCmdRet = RWDev.CloseNetPort(frmcomportindex);
                        if (fCmdRet == 0) frmcomportindex = -1;
                        Thread.Sleep(1000);
                    }
                    fComAdr = 255;
                    string ipAddress = ipServerIP.IpAddressStr;
                    int nPort = Convert.ToInt32(tb_Port.Text);
                    fCmdRet = RWDev.OpenNetPort(nPort, ipAddress, ref fComAdr, ref frmcomportindex);
                    if (fCmdRet == 0)
                    {
                        if (frmcomportindex > 0)
                            RWDev.InitRFIDCallBack(elegateRFIDCallBack, true, frmcomportindex);
                    }
                }
            }
            if (CardNum == 0)//无标签
            {
                AA_times++;
                if (AA_times > targettimes)
                {
                    AA_times = 0;
                    if (Session > 1)
                        Target = (byte)(1 - Target);
                    else
                        Target = 0;
                }
            }
            else
            {
                AA_times = 0;
                if (intervalTime != 0)
                    Thread.Sleep((delayTime + intervalTime) * 100);
            }

            IntPtr ptrWnd1 = IntPtr.Zero;
            ptrWnd1 = FindWindow(null, "UHFReader DS7 Demo V1.1");
            if (ptrWnd1 != IntPtr.Zero)         // 检查当前统计窗口是否打开
            {
                string para = fCmdRet.ToString();
                SendMessage(ptrWnd1, WM_SENDSTATU, IntPtr.Zero, para);
            }
            ptrWnd1 = IntPtr.Zero;


        }

        private void dataGridView6_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        bool isReadTemp = false;
        private void button3_Click_1(object sender, EventArgs e)
        {
            if (button3.Text == ResourceCulture.GetString("btn_inventory_start"))
            {
                if (ledthread == null)
                {

                    byte ANT = 0;
                    byte ANT1 = 0;
                    byte SetOnce = 0;
                    if (AntennaNum == 4)
                    {
                        SetOnce = 0x80;
                        ANT = (byte)comboBox2.SelectedIndex;
                        fCmdRet = RWDev.SetAntennaMultiplexing(ref fComAdr, (byte)(ANT | SetOnce), frmcomportindex);
                    }
                    else if (AntennaNum == 8)
                    {
                        SetOnce = 1;//不保存
                        ANT = (byte)(1 << comboBox2.SelectedIndex);

                        fCmdRet = RWDev.SetAntenna(ref fComAdr, SetOnce, ANT1, ANT, frmcomportindex);
                    }
                    else if (AntennaNum == 16)
                    {
                        SetOnce = 1;//不保存
                        if (comboBox2.SelectedIndex < 8)
                        {
                            ANT = (byte)(1 << comboBox2.SelectedIndex);
                        }
                        else
                        {
                            ANT1 = (byte)(1 << (comboBox2.SelectedIndex-8));
                        }
                        fCmdRet = RWDev.SetAntenna(ref fComAdr, SetOnce, ANT1, ANT, frmcomportindex);

                    }


                    isReadTemp = checkBox13.Checked;
                    Qvalue = (byte)comboBox8.SelectedIndex;
                    Session = (byte)comboBox7.SelectedIndex;
                    Target = (byte)comboBox5.SelectedIndex;
                    targettimes = Convert.ToByte(textBox3.Text, 10);
                    InAnt = (byte)(comboBox2.SelectedIndex | 0x80);

                    if (isReadTemp==false)
                    {
                        epclist.Clear();
                        dataGridView7.Columns.Clear();
                        dataGridView7.DataSource = null;
                        workType = 0;
                    }
                    else
                    {
                        if (dataGridView7.DataSource == null || dataGridView7.Rows.Count == 0) return;
                    }

                    button3.Text = ResourceCulture.GetString("btn_inventory_stop");
                    AA_times = 0;

                    curList.Clear();
                    timer_answer.Enabled = true;
                    reflasg = false;
                    StopLedThread = false;
                    ledthread = new Thread(new ThreadStart(StartReadTemp));
                    ledthread.IsBackground = true;
                    ledthread.Start();
                }
            }
            else
            {
                StopLedThread = true;
            }
        }


        private void StartReadTemp()
        {
            while (!StopLedThread)
            {
                if (isReadTemp == false)//查询标签
                {
                    byte Ant = 0;
                    int TagNum = 0;
                    int Totallen = 0;
                    byte[] EPC = new byte[50000];
                    byte MaskMem = 0;
                    byte[] MaskAdr = new byte[2];
                    byte MaskLen = 0;
                    byte[] MaskData = new byte[100];
                    byte MaskFlag = 0;
                    MaskFlag = 0;
                    int cbtime = System.Environment.TickCount;
                    CardNum = 0;
                    tagrate = 0;
                    NewCardNum = 0;
                    TIDFlag = 0;
                    MaskFlag = 0;
                    FastFlag = 1;
                    fCmdRet = RWDev.Inventory_G2(ref fComAdr, Qvalue, Session, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, tidAddr, tidLen, TIDFlag, Target, InAnt, Scantime, FastFlag, EPC, ref Ant, ref Totallen, ref TagNum, frmcomportindex);
                    int cmdTime = System.Environment.TickCount - cbtime;//命令时间
                    if ((fCmdRet != 0x01) && (fCmdRet != 0x02) && (fCmdRet != 0xF8) && (fCmdRet != 0xF9) && (fCmdRet != 0xEE) && (fCmdRet != 0xFF))
                    {
                        if (rb_tcp.Checked)
                        {
                            if ((frmcomportindex > 0) && (frmcomportindex < 256))
                            {
                                fCmdRet = RWDev.CloseNetPort(frmcomportindex);
                                if (fCmdRet == 0) frmcomportindex = -1;
                                Thread.Sleep(1000);
                            }
                            fComAdr = 255;
                            string ipAddress = ipServerIP.IpAddressStr;
                            int nPort = Convert.ToInt32(tb_Port.Text);
                            fCmdRet = RWDev.OpenNetPort(nPort, ipAddress, ref fComAdr, ref frmcomportindex);
                            if (fCmdRet == 0)
                            {
                                if (frmcomportindex > 0)
                                    RWDev.InitRFIDCallBack(elegateRFIDCallBack, true, frmcomportindex);
                            }
                        }
                    }
                    if (fCmdRet == 0x30)
                    {
                        CardNum = 0;
                    }
                    if (CardNum == 0)
                    {
                        if (Session > 1)
                            AA_times = AA_times + 1;//没有得到标签只更新状态栏
                        if (AA_times > targettimes)
                        {
                            Target = (byte)(1 - Target);
                            AA_times = 0;
                        }
                    }
                    else
                    {
                            AA_times = 0;
                    }

                    IntPtr ptrWnd1 = IntPtr.Zero;
                    ptrWnd1 = FindWindow(null, "UHFReader DS7 Demo V1.1");
                    if (ptrWnd1 != IntPtr.Zero)         // 检查当前统计窗口是否打开
                    {
                        string para = fCmdRet.ToString();
                        SendMessage(ptrWnd1, WM_SENDSTATU, IntPtr.Zero, para);
                    }
                    ptrWnd1 = IntPtr.Zero;
                }
                else
                {
                    for (int m = 0; m < dataGridView7.RowCount; m++)
                    {
                        if (StopLedThread) break;
                        string EPC = dataGridView7.Rows[m].Cells[1].Value.ToString();
                        string temp = readTemp(EPC);
                        this.Invoke((EventHandler)delegate
                        {
                            dataGridView7.Rows[m].Cells[4].Value = temp;
                        });

                    }
                }
            }


            this.Invoke((EventHandler)delegate
            {
                button3.Text = ResourceCulture.GetString("btn_inventory_start");
                ledthread = null;
            });
        }
       // double ab = 0.000000000f;
        private string readTemp(string str)
        {
            byte WordPtr, ENum;
            byte Num = 0;
            byte Mem = 0;
            byte[] CardData = new byte[320];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
 
            ENum = Convert.ToByte(str.Length / 4);
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            Mem = 3;
            WordPtr = 28;
            Num = 4;
            fPassWord = HexStringToByteArray("00000000");
            for (int p = 0; p < 5; p++)
            {
                fCmdRet = RWDev.ReadData_G2(ref fComAdr, EPC, ENum, Mem, WordPtr, Num, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, CardData, ref ferrorcode, frmcomportindex);
                if (fCmdRet == 0) break;
            }
            if (fCmdRet != 0)
            {
                return "N/A";
            }
            int calType = 0;
            int itune = 0;
            double A = 0.00f, B = 0.00f, C = 0.00f, D = 0.00f;
            if (CardData[0] == 0x00 && CardData[1] == 0x00 && CardData[2] == 0x00 && CardData[3] == 0x00 && CardData[4] == 0x00 && CardData[5] == 0x00)//单点
            {
                calType = 0;
                itune = 0;
                if ((CardData[6] == 1) && (CardData[7] == 0))
                {
                    itune = 0;
                }
                else if (CardData[6] == 1)
                {
                    itune = Convert.ToInt32("-" + CardData[7].ToString());
                }
                else
                {
                    itune = Convert.ToInt32(CardData[7].ToString());
                }
            }
            else
            {
                calType = 1;
                short pa, pb, pc, pd;
                pa = (short)(CardData[0] * 256 + CardData[1]);
                pb = (short)(CardData[2] * 256 + CardData[3]);
                pc = (short)(CardData[4] * 256 + CardData[5]);
                pd = (short)(CardData[6] * 256 + CardData[7]);
                A = pa * (10E-12);
                B = pb * (10E-9);
                C = pc * (10E-6);
                D = (-1)*pd * (10E-3);
            }
            byte[]tempData = new byte[2];
            for (int p = 0; p < 5; p++)
            {
                fCmdRet = RWDev.GetBxTagTemperature(ref fComAdr, ENum, EPC, tempData, ref ferrorcode, frmcomportindex);
                if (fCmdRet == 0) break;
            }
            if (fCmdRet==0)
            {

                string temp = "";
                double t = 0.00f;
                int n = (tempData[0] & 255) * 256 + (tempData[1] & 255);
                if (n == 0) return "N/A";
                if (calType == 0)
                {
                    t = ((n + itune - 500) / 5.4817) + 24.9;
                }
                else
                {
                    t = A * Math.Pow(n, 3) + B * Math.Pow(n, 2) + C * Math.Pow(n, 1) + D;
                }
                temp = String.Format("{0:N2}", t) + "℃";
                return temp;
            }
            return "N/A";
        }
        bool isReadSta = false;
        int VBLType = 0;
         
        private void button4_Click_1(object sender, EventArgs e)
        {
            if (button4.Text == ResourceCulture.GetString("btn_inventory_start"))
            {
                if (ledthread == null)
                {
                    byte ANT = 0;
                    byte ANT1 = 0;
                    byte SetOnce = 0;
                    if (AntennaNum == 4)
                    {
                        SetOnce = 0x80;
                        ANT = (byte)comboBox2.SelectedIndex;
                        fCmdRet = RWDev.SetAntennaMultiplexing(ref fComAdr, (byte)(ANT | SetOnce), frmcomportindex);
                    }
                    else if (AntennaNum == 8)
                    {
                        SetOnce = 1;//不保存
                        ANT = (byte)(1 << comboBox2.SelectedIndex);

                        fCmdRet = RWDev.SetAntenna(ref fComAdr, SetOnce, ANT1, ANT, frmcomportindex);
                    }
                    else if (AntennaNum == 16)
                    {
                        SetOnce = 1;//不保存
                        if (comboBox2.SelectedIndex < 8)
                        {
                            ANT = (byte)(1 << comboBox2.SelectedIndex);
                        }
                        else
                        {
                            ANT1 = (byte)(1 << (comboBox2.SelectedIndex - 8));
                        }
                        fCmdRet = RWDev.SetAntenna(ref fComAdr, SetOnce, ANT1, ANT, frmcomportindex);

                    }

                    isReadSta = checkBox16.Checked;
                    Qvalue = (byte)comboBox15.SelectedIndex;
                    Session = (byte)comboBox14.SelectedIndex;
                    Target = (byte)comboBox13.SelectedIndex;
                    targettimes = Convert.ToByte(textBox4.Text, 10);
                    InAnt = (byte)(comboBox12.SelectedIndex | 0x80);
                    VBLType = (byte)comboBox17.SelectedIndex;
                    if (isReadSta == false)
                    {
                        epclist.Clear();
                        dataGridView8.Columns.Clear();
                        dataGridView8.DataSource = null;
                        workType = 0;
                        timer_answer.Enabled = true;
                    }
                    else
                    {
                        if (dataGridView8.DataSource == null || dataGridView8.Rows.Count == 0) return;
                        timer_answer.Enabled = false;
                        byte cfgNo = 0x15;
                        byte len = 1;
                        byte[]cfgData = new byte[256];
                        cfgData[0] = 0;
                        fCmdRet = RWDev.SetCfgParameter(ref fComAdr, (byte)1, cfgNo, cfgData, len, frmcomportindex);
                    }

                    button4.Text = ResourceCulture.GetString("btn_inventory_stop");
                    AA_times = 0;

                    curList.Clear();
                    
                    reflasg = false;
                    StopLedThread = false;
                    ledthread = new Thread(new ThreadStart(StartReadSta));
                    ledthread.IsBackground = true;
                    ledthread.Start();
                }
            }
            else
            {
                StopLedThread = true;
            }
        }

        private void StartReadSta()
        {
            while (!StopLedThread)
            {
                if (isReadSta == false)//查询标签
                {
                    byte Ant = 0;
                    int TagNum = 0;
                    int Totallen = 0;
                    byte[] EPC = new byte[50000];
                    byte MaskMem = 0;
                    byte[] MaskAdr = new byte[2];
                    byte MaskLen = 0;
                    byte[] MaskData = new byte[100];
                    byte MaskFlag = 0;
                    MaskFlag = 0;
                    int cbtime = System.Environment.TickCount;
                    CardNum = 0;
                    tagrate = 0;
                    NewCardNum = 0;
                    TIDFlag = 0;
                    MaskFlag = 0;
                    FastFlag = 1;
                    fCmdRet = RWDev.Inventory_G2(ref fComAdr, Qvalue, Session, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, tidAddr, tidLen, TIDFlag, Target, InAnt, Scantime, FastFlag, EPC, ref Ant, ref Totallen, ref TagNum, frmcomportindex);
                    int cmdTime = System.Environment.TickCount - cbtime;//命令时间
                    if ((fCmdRet != 0x01) && (fCmdRet != 0x02) && (fCmdRet != 0xF8) && (fCmdRet != 0xF9) && (fCmdRet != 0xEE) && (fCmdRet != 0xFF))
                    {
                        if (rb_tcp.Checked)
                        {
                            if ((frmcomportindex > 0) && (frmcomportindex < 256))
                            {
                                fCmdRet = RWDev.CloseNetPort(frmcomportindex);
                                if (fCmdRet == 0) frmcomportindex = -1;
                                Thread.Sleep(1000);
                            }
                            fComAdr = 255;
                            string ipAddress = ipServerIP.IpAddressStr;
                            int nPort = Convert.ToInt32(tb_Port.Text);
                            fCmdRet = RWDev.OpenNetPort(nPort, ipAddress, ref fComAdr, ref frmcomportindex);
                            if (fCmdRet == 0)
                            {
                                if (frmcomportindex > 0)
                                    RWDev.InitRFIDCallBack(elegateRFIDCallBack, true, frmcomportindex);
                            }
                        }
                    }
                    if (fCmdRet == 0x30)
                    {
                        CardNum = 0;
                    }
                    if (CardNum == 0)
                    {
                        if (Session > 1)
                            AA_times = AA_times + 1;//没有得到标签只更新状态栏
                        if (AA_times > targettimes)
                        {
                            Target = (byte)(1 - Target);
                            AA_times = 0;
                        }
                    }
                    else
                    {
                        AA_times = 0;
                    }

                    IntPtr ptrWnd1 = IntPtr.Zero;
                    ptrWnd1 = FindWindow(null, "UHFReader DS7 Demo V1.1");
                    if (ptrWnd1 != IntPtr.Zero)         // 检查当前统计窗口是否打开
                    {
                        string para = fCmdRet.ToString();
                        SendMessage(ptrWnd1, WM_SENDSTATU, IntPtr.Zero, para);
                    }
                    ptrWnd1 = IntPtr.Zero;
                }
                else
                {
                    for (int m = 0; m < dataGridView8.RowCount; m++)
                    {
                        if (StopLedThread) break;
                        string EPC = dataGridView8.Rows[m].Cells[1].Value.ToString();
                        string temp = "";
                        if (VBLType == 0)
                        {
                            temp = Readnormal(EPC);
                        }
                        else
                        {
                            string step1 = ReadTruth(EPC, 5);
                            if (step1.Equals("N/A"))
                            {
                                temp = "N/A"; ;
                            }
                            else
                            {
                                if (step1.Equals("B0FF"))
                                {
                                    temp = "TAMPERED";
                                }
                                else if (step1.Equals("B000"))
                                {
                                    string step2 = ReadTruth(EPC, 6);
                                    if (step2.Equals("N/A"))
                                    {
                                        temp = "N/A"; ;
                                    }
                                    else
                                    {
                                        if (step2.Substring(3).Equals("0"))
                                        {
                                            temp = "UNCLOCKED";
                                        }
                                        else
                                        {
                                            temp = "LOCKED";
                                        }
                                    }
                                }
                                else
                                {
                                    temp = "N/A";
                                }
                            }
                        }
                        this.Invoke((EventHandler)delegate
                        {
                            dataGridView8.Rows[m].Cells[4].Value = temp;
                        });

                    }



                }
            }


            this.Invoke((EventHandler)delegate
            {
                button4.Text = ResourceCulture.GetString("btn_inventory_start");
                ledthread = null;
            });
        }


        public string Readnormal(string str)
        {
            byte WordPtr, ENum;
            byte Num = 0;
            byte Mem = 0;
            byte[] CardData = new byte[320];
            byte MaskMem = 0;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
 
            ENum = Convert.ToByte(str.Length / 4);
            byte[] EPC = new byte[ENum * 2];
            EPC = HexStringToByteArray(str);
            Mem = 0;
            WordPtr = 5;
            Num = 1;
            fPassWord = HexStringToByteArray("00000000");
            for (int p = 0; p < 5; p++)
            {
                fCmdRet = RWDev.ReadData_G2(ref fComAdr, EPC, ENum, Mem, WordPtr, Num, fPassWord, MaskMem, MaskAdr, MaskLen, MaskData, CardData, ref ferrorcode, frmcomportindex);
                if (fCmdRet == 0) break;
            }
            if (fCmdRet != 0)
            {
                return "N/A";
            }
            if (CardData[0] == 0xB0 && CardData[1]==0x00)
            {
                return "LOCKED";
            }
            else if (CardData[0] == 0xB0 && CardData[1] == 0xFF)
            {
                return "UNLOCKED";
            }
            return "N/A";
        }
       // string temp="";
        public string ReadTruth(string str,byte startAddr)
        {
            curList.Clear();
            total_tagnum = 0;
            CardNum = 0;
            Psd[0] = Psd[1] = Psd[2] = Psd[3] = 0;
            byte MaskMem = 0x01;
            byte[] MaskAdr = new byte[2];
            byte MaskLen = 0;
            byte[] MaskData = new byte[100];
            MaskAdr[0] = 0x00;
            MaskAdr[1] = 0x20;
            MaskLen = (byte)(str.Length*4);
            MaskData = HexStringToByteArray(str);
            byte[]EPC=new byte[20000];
            byte Ant = 0x00;
            int Totallen = 0;
            int TagNum = 0;
            ReadMem =0x00;
            ReadAdr[0]=0x00;
            ReadAdr[1] = startAddr;
            ReadLen =0x01;
            Target=0;
            MaskFlag = 1;
            fCmdRet = RWDev.InventoryMix_G2(ref fComAdr, Qvalue, Session, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, ReadMem, ReadAdr, ReadLen, Psd, Target, InAnt, Scantime, FastFlag, EPC, ref Ant, ref Totallen, ref TagNum, frmcomportindex);

            if (curList.Count>=2)
            {
                for (int p = 0; p < curList.Count;p++ )
                {
                    RFIDTag ce = curList[p];
                    int gnum = ce.PacketParam;
                    if (gnum < 0x80)//EPC号
                    {
                        lastnum = gnum;
                        if (!ce.UID.Equals(str)) continue;
                        epcandtid = ce.UID;
                    }
                    else//附带数据
                    {
                        if (((lastnum & 0x7F) == ((gnum & 0x7F) - 1)) || ((lastnum & 0x7F) == 127 && ((gnum & 0x7F) == 0)))//相邻的滚码
                        {
                            return ce.UID;

                        }
                    }
                }
            }
            Target=1;
            curList.Clear();
            total_tagnum = 0;
            CardNum = 0;
            fCmdRet = RWDev.InventoryMix_G2(ref fComAdr, Qvalue, Session, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, ReadMem, ReadAdr, ReadLen, Psd, Target, InAnt, Scantime, FastFlag, EPC, ref Ant, ref Totallen, ref TagNum, frmcomportindex);
            if (curList.Count>=2)
            {
                for (int p = 0; p < curList.Count;p++ )
                {
                    RFIDTag ce = curList[p];
                    int gnum = ce.PacketParam;
                    if (gnum < 0x80)//EPC号
                    {
                        lastnum = gnum;
                        if (!ce.UID.Equals(str)) continue;
                        epcandtid = ce.UID;
                    }
                    else//附带数据
                    {
                        if (((lastnum & 0x7F) == ((gnum & 0x7F) - 1)) || ((lastnum & 0x7F) == 127 && ((gnum & 0x7F) == 0)))//相邻的滚码
                        {
                            return ce.UID;
                        }
                    }
                }
            }
            return "N/A";
        }

        private void btn_language_Click(object sender, EventArgs e)
        {      
            if (radio_ch.Checked)
            {
                lang = LangZh;
            }
            if (radio_en.Checked)
            {
                lang = string.Empty;
            }
            ResourceCulture.SetLang(lang, this, typeof(Form1));
            //string a = ResourceCulture.GetString("failed_export");
            SetListViewHeaderGlobalization();
            try
            {
                Config.PutINI("SysConfig", "Language", lang, iniPath);
            }
            catch (Exception)
            {
                MessageBox.Show(ResourceCulture.GetString("err_save_xml"));
            }
        }

        private void SetListViewHeaderGlobalization()
        {
            if (string.Equals(LangZh, lang))
            {
               
                columnHeader5.Text = "序号";
                columnHeader6.Text = "ID号";
                columnHeader7.Text = "次数";
                deviceName.Text = "名称";
                deviceIP.Text = "IP地址";
                deviceMac.Text = "Mac地址";
                columnHeader1.Text = "序号";
                columnHeader9.Text = "用户名/设备名";
            }
            else
            {
               
                columnHeader5.Text = "No.";
                columnHeader6.Text = "Tag ID ";
                columnHeader7.Text = "Count";

                deviceName.Text = "Device name";
                deviceIP.Text = "Device ip";
                deviceMac.Text = "Device mac";
                columnHeader1.Text = "No.";
                columnHeader9.Text = "User/Device";
            }
        }

        private void groupBox11_Enter(object sender, EventArgs e)
        {

        }

        private void txtIpaddr_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = ("0123456789.".IndexOf(Char.ToUpper(e.KeyChar)) < 0);
        }

        private void btSetIp_Click(object sender, EventArgs e)
        {
            try
            {
                if ((txtIpaddr.Text == "") || (txtSubnet.Text == "") || (txtGateway.Text == ""))
                {
                    return;
                }
                string[] temp1 = txtIpaddr.Text.Split('.');
                string[] temp2 = txtSubnet.Text.Split('.');
                string[] temp3 = txtGateway.Text.Split('.');
                if ((temp1.Length != 4) || (temp2.Length != 4) || (temp3.Length != 4))
                {
                    return;
                }
                byte[] ipAddr = new byte[4];
                byte[] SubnetMask = new byte[4];
                byte[] wgAddr = new byte[4];
                byte dhcp = 0;
                for (int i = 0; i < 4; i++)
                {
                    ipAddr[i] = Convert.ToByte(temp1[i], 10);
                    SubnetMask[i] = Convert.ToByte(temp2[i], 10);
                    wgAddr[i] = Convert.ToByte(temp3[i], 10);
                }
                if (rb_dhcp.Checked) dhcp = 1;
                fCmdRet = RWDev.SetNetWorkIP(ref fComAdr, ipAddr, SubnetMask, wgAddr, dhcp, 0, frmcomportindex);
                if (fCmdRet != 0)
                {
                    string strLog = ResourceCulture.GetString("log_set_failed") + ","+ GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_set_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }

            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void btGetIp_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] ipAddr = new byte[4];
                byte[] SubnetMask = new byte[4];
                byte[] wgAddr = new byte[4];
                byte dhcp = 0;
                txtIpaddr.Text = "";
                txtSubnet.Text = "";
                txtGateway.Text = "";
                fCmdRet = RWDev.GetNetWorkIP(ref fComAdr, ipAddr, SubnetMask, wgAddr, ref dhcp, 0, frmcomportindex);
                if (fCmdRet == 0)
                {
                    txtIpaddr.Text = ipAddr[0].ToString() + "." + ipAddr[1].ToString() + "." + ipAddr[2].ToString() + "." + ipAddr[3].ToString();
                    txtSubnet.Text = SubnetMask[0].ToString() + "." + SubnetMask[1].ToString() + "." + SubnetMask[2].ToString() + "." + SubnetMask[3].ToString();
                    txtGateway.Text = wgAddr[0].ToString() + "." + wgAddr[1].ToString() + "." + wgAddr[2].ToString() + "." + wgAddr[3].ToString();
                    if (dhcp == 1)
                        rb_dhcp.Checked = true;
                    else
                        rb_static.Checked = true;
                    string strLog =  GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog,0);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_get_failed") +"," +GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void btSetconnect_Click(object sender, EventArgs e)
        {
            try
            {
                if ((txtSvrIp.Text == "") || (txtSvrPort.Text == "") || (txtLoclPort.Text == ""))
                {
                    return;
                }
                string[] temp1 = txtSvrIp.Text.Split('.');
                if (temp1.Length != 4)
                {
                    return;
                }
                byte[] SvripAddr = new byte[4];
                int SvrPOrt = 0;
                byte ConnectionMode = 0;
                int ClientPort = 0;

                for (int i = 0; i < 4; i++)
                {
                    SvripAddr[i] = Convert.ToByte(temp1[i], 10);
                }
                SvrPOrt = Convert.ToInt32(txtSvrPort.Text, 10);
                ClientPort = Convert.ToInt32(txtLoclPort.Text, 10);
                ConnectionMode = (byte)com_contype.SelectedIndex;
                fCmdRet = RWDev.SetNetWorkConnection(ref fComAdr, SvripAddr, SvrPOrt, ConnectionMode, ClientPort, 0, frmcomportindex);
                if (fCmdRet != 0)
                {
                    string strLog = ResourceCulture.GetString("log_set_failed") +","+ GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_set_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void btGetconnect_Click(object sender, EventArgs e)
        {
            try
            {
                txtSvrIp.Text = "";
                txtSvrPort.Text = "";
                txtLoclPort.Text = "";
                byte[] SvripAddr = new byte[4];
                int SvrPOrt = 0;
                byte ConnectionMode = 0;
                int ClientPort = 0;
                fCmdRet = RWDev.GetNetWorkConnection(ref fComAdr, SvripAddr, ref SvrPOrt, ref ConnectionMode, ref ClientPort, 0, frmcomportindex);
                if (fCmdRet == 0)
                {
                    txtSvrIp.Text = SvripAddr[0].ToString() + "." + SvripAddr[1].ToString() + "." + SvripAddr[2].ToString() + "." + SvripAddr[3].ToString();
                    txtSvrPort.Text = Convert.ToString(SvrPOrt, 10);
                    txtLoclPort.Text = Convert.ToString(ClientPort, 10);
                    com_contype.SelectedIndex = ConnectionMode;
                    string strLog = ResourceCulture.GetString("log_get_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_get_failed") +","+ GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
               
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void btSetTimeout_Click(object sender, EventArgs e)
        {
            try
            {
                byte TCPReconnectMode = (byte)cbb_Reconnect.SelectedIndex;
                fCmdRet = RWDev.SetReconnect(ref fComAdr, TCPReconnectMode, 0, frmcomportindex);
                if (fCmdRet != 0)
                {
                    string strLog = ResourceCulture.GetString("log_set_failed") +","+ GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_set_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void btGetTimeout_Click(object sender, EventArgs e)
        {
            try
            {
                byte TCPReconnectMode = 0;
                fCmdRet = RWDev.GetReconnect(ref fComAdr, ref TCPReconnectMode, 0, frmcomportindex);
                if (fCmdRet == 0)
                {
                    cbb_Reconnect.SelectedIndex = TCPReconnectMode;
                    string strLog = ResourceCulture.GetString("log_get_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_get_failed") +","+ GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void rj45_get_mac_Click(object sender, EventArgs e)
        {
            byte[] MAC = new byte[6];
            rj45_mac.Text = "";
            fCmdRet = RWDev.GetRJ45MacAddr(ref fComAdr, MAC, frmcomportindex);
            if (fCmdRet == 0)
            {
                rj45_mac.Text = Convert.ToString(MAC[0], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[1], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[2], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[3], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[4], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[5], 16).PadLeft(2, '0');
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") +","+ GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void button28_Click(object sender, EventArgs e)
        {
            byte rj45state = 0;
            byte[] localIP = new byte[4];
            byte[] subnet = new byte[4];
            byte[] gatewayIp = new byte[4];
            txt_rj45_status.Text = "";
            fCmdRet = RWDev.ReadRJ45ConnectStatus(ref fComAdr, ref rj45state, localIP, subnet, gatewayIp, frmcomportindex);
            if (fCmdRet == 0)
            {
                //txt_rj45_status
                string temp = "";
                if (rj45state == 0)
                    temp = ResourceCulture.GetString("str_plhgged");
                else if (rj45state == 1)
                    temp = ResourceCulture.GetString("str_not_insert");
                else if (rj45state == 255)
                    temp = ResourceCulture.GetString("Hardware_error");
                int length = temp.Length;
                string ip = localIP[0] + "." + localIP[1] + "." + localIP[2] + "." + localIP[3];
                string net = subnet[0] + "." + subnet[1] + "." + subnet[2] + "." + subnet[3];
                string wayip = gatewayIp[0] + "." + gatewayIp[1] + "." + gatewayIp[2] + "." + gatewayIp[3];
                temp += "\t";

                temp += ResourceCulture.GetString("current_ip") + ip + "\r\n";
                temp += "\t\t" + ResourceCulture.GetString("current_subnet") + net + "\r\n";
                temp += "\t\t" + ResourceCulture.GetString("current_gateway") + wayip;
                txt_rj45_status.Text = temp;
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") +","+ GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void btGetKeepAlive_Click(object sender, EventArgs e)
        {
            try
            {
                txt_keepalive_time.Text = "";
                byte keepaliveen = 0;
                int keepalivetime = 0;
                fCmdRet = RWDev.GetKeepAlive(ref fComAdr, ref keepaliveen, ref keepalivetime, 0, frmcomportindex);
                if (fCmdRet == 0)
                {
                    cbb_keepalive_en.SelectedIndex = keepaliveen;
                    txt_keepalive_time.Text = keepalivetime + "";
                    string strLog = ResourceCulture.GetString("log_get_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_get_failed") + ","+GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void btSetKeepAlive_Click(object sender, EventArgs e)
        {
            try
            {
                if (txt_keepalive_time.Text == "")
                {
                    return;
                }

                byte keepaliveen = (byte)cbb_keepalive_en.SelectedIndex;
                int keepalivetime = Convert.ToInt32(txt_keepalive_time.Text, 10);

                fCmdRet = RWDev.SetKeepAlive(ref fComAdr, keepaliveen, keepalivetime, 0, frmcomportindex);
                if (fCmdRet != 0)
                {
                    string strLog = ResourceCulture.GetString("log_set_failed") +","+ GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_set_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void wifi_btSetIp_Click(object sender, EventArgs e)
        {
            try
            {
                if ((wifi_txtIpaddr.Text == "") || (wifi_txtSubnet.Text == "") || (wifi_txtGateway.Text == ""))
                {
                    return;
                }
                string[] temp1 = wifi_txtIpaddr.Text.Split('.');
                string[] temp2 = wifi_txtSubnet.Text.Split('.');
                string[] temp3 = wifi_txtGateway.Text.Split('.');
                if ((temp1.Length != 4) || (temp2.Length != 4) || (temp3.Length != 4))
                {
                    return;
                }
                byte[] ipAddr = new byte[4];
                byte[] SubnetMask = new byte[4];
                byte[] wgAddr = new byte[4];
                byte dhcp = 0;
                for (int i = 0; i < 4; i++)
                {
                    ipAddr[i] = Convert.ToByte(temp1[i], 10);
                    SubnetMask[i] = Convert.ToByte(temp2[i], 10);
                    wgAddr[i] = Convert.ToByte(temp3[i], 10);
                }
                if (rb_wifi_dhcp.Checked) dhcp = 1;
                fCmdRet = RWDev.SetNetWorkIP(ref fComAdr, ipAddr, SubnetMask, wgAddr, dhcp, 1, frmcomportindex);
                if (fCmdRet != 0)
                {
                    string strLog = ResourceCulture.GetString("log_set_failed") + ","+GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_set_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }

            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void wifi_btGetIp_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] ipAddr = new byte[4];
                byte[] SubnetMask = new byte[4];
                byte[] wgAddr = new byte[4];
                byte dhcp = 0;
                wifi_txtIpaddr.Text = "";
                wifi_txtSubnet.Text = "";
                wifi_txtGateway.Text = "";
                fCmdRet = RWDev.GetNetWorkIP(ref fComAdr, ipAddr, SubnetMask, wgAddr, ref dhcp, 1, frmcomportindex);
                if (fCmdRet == 0)
                {
                    wifi_txtIpaddr.Text = ipAddr[0].ToString() + "." + ipAddr[1].ToString() + "." + ipAddr[2].ToString() + "." + ipAddr[3].ToString();
                    wifi_txtSubnet.Text = SubnetMask[0].ToString() + "." + SubnetMask[1].ToString() + "." + SubnetMask[2].ToString() + "." + SubnetMask[3].ToString();
                    wifi_txtGateway.Text = wgAddr[0].ToString() + "." + wgAddr[1].ToString() + "." + wgAddr[2].ToString() + "." + wgAddr[3].ToString();
                    if (dhcp == 1)
                        rb_wifi_dhcp.Checked = true;
                    else
                        rb_wifi_static.Checked = true;
                    string strLog = ResourceCulture.GetString("log_get_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_get_failed") +","+ GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void wifi_btSetconnect_Click(object sender, EventArgs e)
        {
            try
            {
                if ((wifi_txtSvrIp.Text == "") || (wifi_txtSvrPort.Text == "") || (wifi_txtLoclPort.Text == ""))
                {
                    return;
                }
                string[] temp1 = wifi_txtSvrIp.Text.Split('.');
                if (temp1.Length != 4)
                {
                    return;
                }
                byte[] SvripAddr = new byte[4];
                int SvrPOrt = 0;
                byte ConnectionMode = 0;
                int ClientPort = 0;

                for (int i = 0; i < 4; i++)
                {
                    SvripAddr[i] = Convert.ToByte(temp1[i], 10);
                }
                SvrPOrt = Convert.ToInt32(wifi_txtSvrPort.Text, 10);
                ClientPort = Convert.ToInt32(wifi_txtLoclPort.Text, 10);
                ConnectionMode = (byte)wifi_com_contype.SelectedIndex;
                fCmdRet = RWDev.SetNetWorkConnection(ref fComAdr, SvripAddr, SvrPOrt, ConnectionMode, ClientPort, 1, frmcomportindex);
                if (fCmdRet != 0)
                {
                    string strLog = ResourceCulture.GetString("log_set_failed") + ","+GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_set_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void wifi_btGetconnect_Click(object sender, EventArgs e)
        {
            try
            {
                wifi_txtSvrIp.Text = "";
                wifi_txtSvrPort.Text = "";
                wifi_txtLoclPort.Text = "";
                byte[] SvripAddr = new byte[4];
                int SvrPOrt = 0;
                byte ConnectionMode = 0;
                int ClientPort = 0;
                fCmdRet = RWDev.GetNetWorkConnection(ref fComAdr, SvripAddr, ref SvrPOrt, ref ConnectionMode, ref ClientPort, 1, frmcomportindex);
                if (fCmdRet == 0)
                {
                    wifi_txtSvrIp.Text = SvripAddr[0].ToString() + "." + SvripAddr[1].ToString() + "." + SvripAddr[2].ToString() + "." + SvripAddr[3].ToString();
                    wifi_txtSvrPort.Text = Convert.ToString(SvrPOrt, 10);
                    wifi_txtLoclPort.Text = Convert.ToString(ClientPort, 10);
                    wifi_com_contype.SelectedIndex = ConnectionMode;
                    string strLog = ResourceCulture.GetString("log_get_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_get_failed") + ","+GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

       
        private void wifi_btSetTimeout_Click(object sender, EventArgs e)
        {
            try
            {
                byte TCPReconnectMode = (byte)wifi_cbb_Reconnect.SelectedIndex;
                fCmdRet = RWDev.SetReconnect(ref fComAdr, TCPReconnectMode, 1, frmcomportindex);
                if (fCmdRet != 0)
                {
                    string strLog = ResourceCulture.GetString("log_set_failed") +","+ GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_set_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void wifi_btGetTimeout_Click(object sender, EventArgs e)
        {
            try
            {
                byte TCPReconnectMode = 0;
                fCmdRet = RWDev.GetReconnect(ref fComAdr, ref TCPReconnectMode, 1, frmcomportindex);
                if (fCmdRet == 0)
                {
                    wifi_cbb_Reconnect.SelectedIndex = TCPReconnectMode;
                    string strLog = ResourceCulture.GetString("log_get_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_get_failed") + ","+GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void btRj45Restart_Click(object sender, EventArgs e)
        {
            fCmdRet = RWDev.ResetReader(ref fComAdr, frmcomportindex);
            if (fCmdRet == 0)
            {
                string strLog = ResourceCulture.GetString("reset_reader_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("reset_reader_failed");
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void wifi_btSetKeepAlive_Click(object sender, EventArgs e)
        {
            try
            {
                if (txt_wifi_keepalive_time.Text == "")
                {
                    return;
                }

                byte keepaliveen = (byte)cbb_wifi_keepalive_en.SelectedIndex;
                int keepalivetime = Convert.ToInt32(txt_wifi_keepalive_time.Text, 10);

                fCmdRet = RWDev.SetKeepAlive(ref fComAdr, keepaliveen, keepalivetime, 1, frmcomportindex);
                if (fCmdRet == 0)
                {
                    string strLog = ResourceCulture.GetString("log_set_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_set_failed") + "," + GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void wifi_btGetKeepAlive_Click(object sender, EventArgs e)
        {
            try
            {
                txt_wifi_keepalive_time.Text = "";
                byte keepaliveen = 0;
                int keepalivetime = 0;
                fCmdRet = RWDev.GetKeepAlive(ref fComAdr, ref keepaliveen, ref keepalivetime, 1, frmcomportindex);
                if (fCmdRet == 0)
                {
                    cbb_wifi_keepalive_en.SelectedIndex = keepaliveen;
                    txt_wifi_keepalive_time.Text = keepalivetime + "";
                    string strLog = ResourceCulture.GetString("log_get_success");
                    WriteLog(lrtxtLog, strLog, 0);
                }
                else
                {
                    string strLog = ResourceCulture.GetString("log_get_failed") + "," + GetReturnCodeDesc(fCmdRet);
                    WriteLog(lrtxtLog, strLog, 1);
                }
            }
            catch (System.Exception ex)
            {
                ex.ToString();
            }
        }

        private void wifi_read_status_Click(object sender, EventArgs e)
        {
            byte wifistate = 0;
            byte[] localIP = new byte[4];
            byte[] subnet = new byte[4];
            byte[] gatewayIp = new byte[4];
            txt_wifi_state.Text = "";
            fCmdRet = RWDev.ReadWIFIConnectStatus(ref fComAdr, ref wifistate, localIP, subnet, gatewayIp, frmcomportindex);
            if (fCmdRet == 0)
            {
                string temp = "";
                if (wifistate == 0)
                    temp = ResourceCulture.GetString("str_connect_ap");
                else if (wifistate == 1)
                    temp = ResourceCulture.GetString("str_not_connect_ap");
                else if (wifistate == 255)
                    temp = ResourceCulture.GetString("not_support_wifi");

                int length = temp.Length;
                string ip = localIP[0] + "." + localIP[1] + "." + localIP[2] + "." + localIP[3];
                string net = subnet[0] + "." + subnet[1] + "." + subnet[2] + "." + subnet[3];
                string wayip = gatewayIp[0] + "." + gatewayIp[1] + "." + gatewayIp[2] + "." + gatewayIp[3];
                temp += "\t";

                temp += ResourceCulture.GetString("current_ip") + ip + "\r\n";
                temp += "\t\t" + ResourceCulture.GetString("current_subnet") + net + "\r\n";
                temp += "\t\t" + ResourceCulture.GetString("current_gateway") + wayip;
                txt_wifi_state.Text = temp;
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + "," + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
           
        }

        private void read_wifi_mac_Click(object sender, EventArgs e)
        {
            byte[] MAC = new byte[6];
            wifi_mac.Text = "";
            fCmdRet = RWDev.GetWIFIMacAddr(ref fComAdr, MAC, frmcomportindex);
            if (fCmdRet == 0)
            {
                wifi_mac.Text = Convert.ToString(MAC[0], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[1], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[2], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[3], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[4], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[5], 16).PadLeft(2, '0');
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + "," + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void wifi_setApConnect_Click(object sender, EventArgs e)
        {
            if (txt_ssid.Text.Trim().Length == 0
               || txt_apmac.Text.Trim().Length != 17)
                return;
           
            byte[] ssid = new byte[256];
           
            byte[] Pwd = new byte[256];
            byte[] MAC = new byte[6];
            ssid = Encoding.UTF8.GetBytes(txt_ssid.Text.Trim());
            byte ssidLen = (byte)ssid.Length;
            if (txt_apsw.Text.Length > 0)
                Pwd = Encoding.ASCII.GetBytes(txt_apsw.Text.Trim());
            byte pwdLen = (byte)Pwd.Length;
            MAC = HexStringToByteArray(txt_apmac.Text.Trim().Replace(":", ""));
            int fCmdRet = RWDev.SetAPConnectName_Pwd(ref fComAdr, ssidLen, ssid, pwdLen, Pwd, MAC, frmcomportindex);
            if (fCmdRet == 0)
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + "," + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void wifi_getApConnect_Click(object sender, EventArgs e)
        {
            byte ssidLen = (byte)txt_ssid.Text.Trim().Length;
            byte[] ssid = new byte[256];
            byte pwdLen = (byte)txt_apsw.Text.Trim().Length;
            byte[] Pwd = new byte[256];
            byte[] MAC = new byte[6];
            int fCmdRet = RWDev.GetAPConnectName_Pwd(ref fComAdr, ref ssidLen, ssid, ref pwdLen, Pwd, MAC, frmcomportindex);
            if (fCmdRet == 0)
            {
                if (ssidLen > 0)
                {
                    byte[] daw = new byte[ssidLen];
                    Array.Copy(ssid, 0, daw, 0, ssidLen);
                    txt_ssid.Text = Encoding.UTF8.GetString(daw);
                }
                if (pwdLen > 0)
                {
                    byte[] daw = new byte[pwdLen];
                    Array.Copy(Pwd, 0, daw, 0, pwdLen);
                    txt_apsw.Text = Encoding.UTF8.GetString(daw);
                }
                txt_apmac.Text = Convert.ToString(MAC[0], 16).PadLeft(2, '0').ToUpper() + ":"
                    + Convert.ToString(MAC[1], 16).PadLeft(2, '0').ToUpper() + ":"
                    + Convert.ToString(MAC[2], 16).PadLeft(2, '0').ToUpper() + ":"
                    + Convert.ToString(MAC[3], 16).PadLeft(2, '0').ToUpper() + ":"
                    + Convert.ToString(MAC[4], 16).PadLeft(2, '0').ToUpper() + ":"
                    + Convert.ToString(MAC[5], 16).PadLeft(2, '0').ToUpper();
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + "," + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void btWifiRestart_Click(object sender, EventArgs e)
        {
            fCmdRet = RWDev.ResetReader(ref fComAdr, frmcomportindex);
            if (fCmdRet == 0)
            {
                string strLog = ResourceCulture.GetString("reset_reader_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("reset_reader_failed");
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void btwificlear_Click(object sender, EventArgs e)
        {
            dataGridView9.Rows.Clear();
        }

        public static Thread mthread = null;
        private void wifi_search_Click(object sender, EventArgs e)
        {
            if (mthread == null)
            {
                dataGridView9.Rows.Clear();
                mthread = new Thread(new ThreadStart(searchwifi));
                mthread.IsBackground = true;
                mthread.Start();
            }
        }

        private void searchwifi()
        {
            byte[] APInfo = new byte[25600];
            int length = 0;
            int Count = 0;
            fCmdRet = RWDev.SearchWIFI(ref fComAdr, APInfo, ref length, ref Count, frmcomportindex);
            if (fCmdRet != 0x30 && Count > 0)
            {
                int pos = 0;
                for (int m = 0; m < Count; m++)
                {
                    byte ssidLen = APInfo[pos];
                    pos++;
                    byte[] ssid = new byte[ssidLen];
                    Array.Copy(APInfo, pos, ssid, 0, ssidLen);
                    pos += ssidLen;
                    byte rssi = APInfo[pos];
                    pos++;
                    byte[] MAC = new byte[6];
                    Array.Copy(APInfo, pos, MAC, 0, 6);
                    pos += 6;
                    byte Channel = APInfo[pos];
                    pos++;
                    string[] temp = new string[5];
                    temp[0] = dataGridView9.RowCount + 1 + "";
                    temp[1] = Encoding.UTF8.GetString(ssid);
                    temp[2] = Convert.ToString(MAC[0], 16).PadLeft(2, '0').ToUpper() + ":"
                    + Convert.ToString(MAC[1], 16).PadLeft(2, '0').ToUpper() + ":"
                    + Convert.ToString(MAC[2], 16).PadLeft(2, '0').ToUpper() + ":"
                    + Convert.ToString(MAC[3], 16).PadLeft(2, '0').ToUpper() + ":"
                    + Convert.ToString(MAC[4], 16).PadLeft(2, '0').ToUpper() + ":"
                    + Convert.ToString(MAC[5], 16).PadLeft(2, '0').ToUpper();
                    temp[3] = Channel + "";
                    temp[4] = (rssi - 256) + "";
                    this.Invoke((EventHandler)delegate
                    {
                        dataGridView9.Rows.Add(temp);
                    });
                }
            }
            mthread = null;
        }

        private void btSetAntTime_Click(object sender, EventArgs e)
        {
            byte AntSWTime = 0;
            byte cfgNo = 72;
            byte[] cfgData = new byte[256];
            int len = 2;
            AntSWTime = (byte)cbb_ant_dwelltime.SelectedIndex;
            cfgData[0] = 0;
            cfgData[1] = AntSWTime;
            int fCmdRet = RWDev.SetCfgParameter(ref fComAdr, 0, cfgNo, cfgData, len, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btGetAntTime_Click(object sender, EventArgs e)
        {
            byte cfgNo = 72;
            byte[] cfgData = new byte[256];
            int len = 0;
            int fCmdRet = RWDev.GetCfgParameter(ref fComAdr, cfgNo, cfgData, ref len, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                if (len == 2)
                {
                    cbb_ant_dwelltime.SelectedIndex = cfgData[1];
                }
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btGetAlarmRule_Click(object sender, EventArgs e)
        {
            byte cfgNo = 70;
            byte[] cfgData = new byte[256];
            int len = 0;
            int fCmdRet = RWDev.GetCfgParameter(ref fComAdr, cfgNo, cfgData, ref len, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                if (len >=5 )
                {
                    if ((cfgData[0] & 0x01) == 0x01)
                        chk_matchdata.Checked = true;
                    else
                        chk_matchdata.Checked = false;

                    if ((cfgData[0] & 0x02) == 0x02)
                        chk_matchlength.Checked = true;
                    else
                        chk_matchlength.Checked = false;
                    cbb_output.SelectedIndex = cfgData[1];
                    cbb_matchlength.SelectedIndex = cfgData[2];
                    txt_matchAddr.Text = cfgData[3] + "";
                    txt_matchLen.Text = cfgData[4] + "";
                    byte[] daw = new byte[(cfgData[4] + 7) / 8];
                    Array.Copy(cfgData, 5, daw, 0, daw.Length);
                    txt_matchdata.Text = ByteArrayToHexString(daw);
                }
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btSetAlarmRule_Click(object sender, EventArgs e)
        {
            byte MatchEn = 0;
            byte MatchOpt = 0;
            byte MatchEPCLen = 0;
            byte MatchAddr = 0;
            byte MatchLen = 0;
            byte[] MatchData = null;
            byte cfgNo = 70;
            byte[] cfgData = new byte[256];
            if (chk_matchdata.Checked)
                MatchEn |= 0x01;
            if (chk_matchlength.Checked)
                MatchEn |= 0x02;
            MatchOpt = (byte)cbb_output.SelectedIndex;
            MatchEPCLen = (byte)cbb_matchlength.SelectedIndex;
            if (txt_matchAddr.Text.Length == 0 || txt_matchLen.Text.Length == 0)
                return;
            MatchAddr = Convert.ToByte(txt_matchAddr.Text,10);
            MatchLen = Convert.ToByte(txt_matchLen.Text, 10);
            if (txt_matchdata.Text.Length*4 < MatchLen)
            {
                return;
            }
            MatchData = HexStringToByteArray(txt_matchdata.Text);
            int len = 5+ MatchData.Length;
            cfgData[0] = MatchEn;
            cfgData[1] = MatchOpt;
            cfgData[2] = MatchEPCLen;
            cfgData[3] = MatchAddr;
            cfgData[4] = MatchLen;
            Array.Copy(MatchData, 0, cfgData, 5, MatchData.Length);
            int fCmdRet = RWDev.SetCfgParameter(ref fComAdr, 0, cfgNo, cfgData, len, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btSetRelayAction_Click(object sender, EventArgs e)
        {
            byte ActTime = 0;
            byte cfgNo = 71;
            byte[] cfgData = new byte[256];
            int len = 2;
            ActTime = (byte)cbb_relaytime.SelectedIndex;
            cfgData[0] = 0;
            if (chk_relay1.Checked) cfgData[0] |= 0x01;
            if (chk_relay2.Checked) cfgData[0] |= 0x02;
            if (chk_relay3.Checked) cfgData[0] |= 0x04;
            if (chk_relay4.Checked) cfgData[0] |= 0x08;
            cfgData[1] = ActTime;
            int fCmdRet = RWDev.SetCfgParameter(ref fComAdr, 0, cfgNo, cfgData, len, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void btGetRelayAction_Click(object sender, EventArgs e)
        {
            byte cfgNo = 71;
            byte[] cfgData = new byte[256];
            int len = 0;
            int fCmdRet = RWDev.GetCfgParameter(ref fComAdr, cfgNo, cfgData, ref len, frmcomportindex);
            if (fCmdRet != 0)
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
            else
            {
                if (len == 2)
                {
                    cbb_relaytime.SelectedIndex = cfgData[1];
                    if ((cfgData[0] & 0x01) == 0x01)
                        chk_relay1.Checked = true;
                    else
                        chk_relay1.Checked = false;

                    if ((cfgData[0] & 0x02) == 0x02)
                        chk_relay2.Checked = true;
                    else
                        chk_relay2.Checked = false;

                    if ((cfgData[0] & 0x04) == 0x04)
                        chk_relay3.Checked = true;
                    else
                        chk_relay3.Checked = false;

                    if ((cfgData[0] & 0x08) == 0x08)
                        chk_relay4.Checked = true;
                    else
                        chk_relay4.Checked = false;

                }
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
        }

        private void Form1_QueryAccessibilityHelp(object sender, QueryAccessibilityHelpEventArgs e)
        {

        }

        private void read_blue_mac_Click(object sender, EventArgs e)
        {
            byte[] MAC = new byte[6];
            bluetooth_mac.Text = "";
            fCmdRet = RWDev.GetBluetoothMacAddr(ref fComAdr, MAC, frmcomportindex);
            if (fCmdRet == 0)
            {
                bluetooth_mac.Text = Convert.ToString(MAC[0], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[1], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[2], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[3], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[4], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[5], 16).PadLeft(2, '0');
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void read_ble_mac_Click(object sender, EventArgs e)
        {
            byte[] MAC = new byte[6];
            ble_mac.Text = "";
            fCmdRet = RWDev.GetBleMacAddr(ref fComAdr, MAC, frmcomportindex);
            if (fCmdRet == 0)
            {
                ble_mac.Text = Convert.ToString(MAC[0], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[1], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[2], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[3], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[4], 16).PadLeft(2, '0') + ":"
                              + Convert.ToString(MAC[5], 16).PadLeft(2, '0');
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void set_blue_name_Click(object sender, EventArgs e)
        {
            byte namelen = 0;
            byte[] BTName = null;
            if (bluetooth_name.Text.Trim().Length == 0) return;
            BTName = Encoding.UTF8.GetBytes(bluetooth_name.Text.Trim());
            namelen = (byte)BTName.Length;
            fCmdRet = RWDev.SetBluetoothNme(ref fComAdr, namelen, BTName, frmcomportindex);
            if (fCmdRet==0)
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void get_blue_name_Click(object sender, EventArgs e)
        {
            byte namelen = 0;
            byte[] BTName = new byte[256];
            bluetooth_name.Text = "";
            fCmdRet = RWDev.GetBluetoothNme(ref fComAdr, ref namelen, BTName, frmcomportindex);
            if (fCmdRet == 0)
            {
                bluetooth_name.Text = Encoding.UTF8.GetString(BTName, 0, namelen);
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void set_ble_name_Click(object sender, EventArgs e)
        {
            byte namelen = 0;
            byte[] BTName = null;
            if (ble_name.Text.Trim().Length == 0) return;
            BTName = Encoding.UTF8.GetBytes(ble_name.Text.Trim());
            namelen = (byte)BTName.Length;
            fCmdRet = RWDev.SetBleNme(ref fComAdr, namelen, BTName, frmcomportindex);
            if (fCmdRet == 0)
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void get_ble_name_Click(object sender, EventArgs e)
        {
            byte namelen = 0;
            byte[] BTName = new byte[256];
            ble_name.Text = "";
            fCmdRet = RWDev.GetBleNme(ref fComAdr, ref namelen, BTName, frmcomportindex);
            if (fCmdRet == 0)
            {
                ble_name.Text = Encoding.UTF8.GetString(BTName, 0, namelen);
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void set_interface_en_Click(object sender, EventArgs e)
        {
            int connIntf = 0x0000;
            if (chk_wifi.Checked)
                connIntf |= 0x0001;
            if (chk_bluetooth.Checked)
                connIntf |= 0x0004;
            if (chk_ble.Checked)
                connIntf |= 0x0008;
            fCmdRet = RWDev.SetCommunicationSwitch(ref fComAdr, connIntf, frmcomportindex);
            if (fCmdRet == 0)
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void get_interface_en_Click(object sender, EventArgs e)
        {
            int connIntf = 0x0000;
            fCmdRet = RWDev.GetCommunicationSwitch(ref fComAdr, ref connIntf, frmcomportindex);
            if (fCmdRet == 0)
            {
                if ((connIntf & 0x0001) == 0x0001)
                    chk_wifi.Checked = true;
                else
                    chk_wifi.Checked = false;

                if ((connIntf & 0x0004) == 0x0004)
                    chk_bluetooth.Checked = true;
                else
                    chk_bluetooth.Checked = false;

                if ((connIntf & 0x0008) == 0x0008)
                    chk_ble.Checked = true;
                else
                    chk_ble.Checked = false;

                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void btSetWiegand_Click(object sender, EventArgs e)
        {
            byte WgCfg = 0;
            byte DataInvl = 0;
            byte PulWidth = 0;
            byte PulsInvl = 0;
            byte OffsetAdr = 0;
            WgCfg = (byte)com_wg_type.SelectedIndex;
            DataInvl = (byte)comboBox9.SelectedIndex;
            PulWidth = (byte)(comboBox10.SelectedIndex+1);
            PulsInvl = (byte)(comboBox16.SelectedIndex+1);
            OffsetAdr = (byte)comboBox18.SelectedIndex;
            fCmdRet = RWDev.SetWieGandParam(ref fComAdr, WgCfg, DataInvl, PulWidth,PulsInvl, OffsetAdr,frmcomportindex);
            if (fCmdRet == 0)
            {
                string strLog = ResourceCulture.GetString("log_set_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_set_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void btGetWiegand_Click(object sender, EventArgs e)
        {
            byte WgCfg = 0;
            byte DataInvl = 0;
            byte PulWidth = 0;
            byte PulsInvl = 0;
            byte OffsetAdr = 0;

            fCmdRet = RWDev.GetWieGandParam(ref fComAdr,ref WgCfg,ref DataInvl,ref PulWidth,ref PulsInvl,ref OffsetAdr, frmcomportindex);
            if (fCmdRet == 0)
            {
                com_wg_type.SelectedIndex = WgCfg;
                comboBox9.SelectedIndex = DataInvl;
                comboBox10.SelectedIndex= PulWidth - 1;
                comboBox16.SelectedIndex = PulsInvl - 1;
                comboBox18.SelectedIndex = OffsetAdr;
                string strLog = ResourceCulture.GetString("log_get_success");
                WriteLog(lrtxtLog, strLog, 0);
            }
            else
            {
                string strLog = ResourceCulture.GetString("log_get_failed") + GetReturnCodeDesc(fCmdRet);
                WriteLog(lrtxtLog, strLog, 1);
            }
        }

        private void btUpdate_Click(object sender, EventArgs e)
        {
            updateForm up = new updateForm();
            up.ShowDialog();
        }
    }
}
