using System;
using System.Text;
using System.Windows.Forms;
using cn.mineki.Reader;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Drawing;
using System.IO;

namespace testReadCardForm
{
    public partial class MK200TestForm : Form
    {
        int succ;
        int total;
        public ReaderPortNum rpNum = ReaderPortNum.HID;

        public MK200TestForm()
        {
            InitializeComponent();
            for(int i=0; i<16; i++)
                cmbM1Sector.Items.Add(i);
            for (int i = 0; i < 4; i++)
                cmbM1Block.Items.Add(i);
            
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void MK200TestForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (progressThread != null)
            {
                progressThread.Abort();
                progressThread.Join();
                progressThread = null;
            }
            IDCardReader.CloseComm();
        }

        private void MK200TestForm_Load(object sender, EventArgs e)
        {
            cmbBlockNum.SelectedIndex = 0;
            cmbCardType.SelectedIndex = 7;
            cmbSCardType.SelectedIndex = 0;
            chkBeep.Checked = true;
            ButtonEnabled(false);
            cmbReaderPort.SelectedIndex = 2;
            cmbM1Sector.SelectedIndex = 0;
            cmbM1Block.SelectedIndex = 0;
            Text = "智能卡读写器演示程序" + Program.Version;
        }
                     
        #region 显示和声音
        private void BeepOne()
        {
            try
            {
                IDCardReader.Buzzer(3, 1, 1);
            }
            catch { }
        }
        private void lsbLog_DrawItem(object sender, DrawItemEventArgs e)
        {
            try
            {
                string s = lsbLog.Items[e.Index].ToString();
                if (s.Contains("失败") || s.Contains("错误"))
                    e.Graphics.DrawString(s, this.Font, Brushes.Red, e.Bounds);
                else if (s.Contains(">>"))//s.Contains("数据") || 
                    e.Graphics.DrawString(s, this.Font, Brushes.Blue, e.Bounds);
                else e.Graphics.DrawString(s, this.Font, Brushes.Green, e.Bounds);
            }
            catch { }
        }
        delegate void delegateWriteLog(string sMsg);
        private void WriteLog(string sMsg)
        {
            if (!this.lsbLog.InvokeRequired)//判断不在线程中访问
            {
                string sLogHead = DateTime.Now.ToString("HH:mm:ss：");
                lsbLog.Items.Add(sLogHead + sMsg);
                lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
                lsbLog.TopIndex = lsbLog.Items.Count - 1;
            }
            else
            {
                delegateWriteLog delePrintLog = new delegateWriteLog(WriteLog);//实现委托
                this.BeginInvoke(delePrintLog, new object[] { sMsg });//异步执行  
            }
        }

        private void WriteErrorLog(string sMsg)
        {
            if (!this.lsbLog.InvokeRequired)//判断不在线程中访问
            {
                string sLogHead = DateTime.Now.ToString("HH:mm:ss：");
                lsbLog.Items.Add(sLogHead + sMsg);
                lsbLog.SelectedIndex = lsbLog.Items.Count - 1;
                lsbLog.TopIndex = lsbLog.Items.Count - 1;
            }
            else
            {
                delegateWriteLog delePrintLog = new delegateWriteLog(WriteErrorLog);//实现委托
                this.BeginInvoke(delePrintLog, new object[] { sMsg });//异步执行  
            }
        }

        delegate void delegateClearLog();
        void ClearLog()
        {
            if (!this.lsbLog.InvokeRequired)//判断不在线程中访问
            {
                lsbLog.Items.Clear();
            }
            else
            {
                delegateClearLog deleClearLog = new delegateClearLog(ClearLog);//实现委托
                this.BeginInvoke(deleClearLog);//异步执行  
            }
        }

        void UpdateLoopTestMessage(string sMsg)
        {
            if (!this.lsbLog.InvokeRequired)//判断不在线程中访问
            {
                //lbRepRead.Text = sMsg;
                tslbStatus.Text = sMsg;
            }
            else
            {
                delegateWriteLog delePrintLog = new delegateWriteLog(UpdateLoopTestMessage);//实现委托
                this.BeginInvoke(delePrintLog, new object[] { sMsg });//异步执行  
            }
        }

        private void PlayOK()
        {
            string SoundLocation = Application.StartupPath + @"\wav\ok.mp3";
            MusicPlayer.PlayMusic(SoundLocation);
        }

        private void PlayInfo(int nInfo)
        {
            string SoundLocation = Application.StartupPath;
            if (nInfo == 0)
                SoundLocation += @"\wav\info_msr_read.mp3";
            else if (nInfo == 1)
                SoundLocation += @"\wav\info_msr_write.mp3";

            MusicPlayer.PlayMusic(SoundLocation);
        }

        private void PlayError(int nError)
        {
            string SoundLocation = Application.StartupPath;
            if (nError == 0)
                SoundLocation += @"\wav\err_dev_open.mp3";
            else if (nError == 1)
                SoundLocation += @"\wav\err_msr.mp3";
            else if (nError == 2)
                SoundLocation += @"\wav\err_other.mp3";
            else if (nError == 3)
                SoundLocation += @"\wav\err_readid.mp3";
            else if (nError == 4)
                SoundLocation += @"\wav\err_rf_apdu.mp3";
            else if (nError == 5)
                SoundLocation += @"\wav\err_rf_poweron.mp3";
            else if (nError == 6)
                SoundLocation += @"\wav\err_sc_apdu.mp3";
            else if (nError == 7)
                SoundLocation += @"\wav\err_sc_poweron.mp3";
            else if (nError == 8)
                SoundLocation += @"\wav\err_checkidcard.mp3";
            else if (nError == 9)
                SoundLocation += @"\wav\err_msr_write2.mp3";
            else if (nError == 10)
                SoundLocation += @"\wav\err_msr_write3.mp3";
            else if (nError == 11)
                SoundLocation += @"\wav\err_msr_timeout.mp3";
            MusicPlayer.PlayMusic(SoundLocation);
        }
        #endregion

        #region 工具函数
        public static byte[] StrToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }

        public static string HexByteToStr(byte[] hexbytes, int bytelen)
        {
            string formattext = "";
            for (int myi = 0; myi < bytelen; myi++)
            {
                formattext += string.Format("{0:X2}", hexbytes[myi]);
            }
            return formattext;
        }

        private static uint bytesToInt(byte[] src, int offset)
        {
            uint value;
            value = (uint)(((src[offset] & 0xFF) << 24)
                    | ((src[offset + 1] & 0xFF) << 16)
                    | ((src[offset + 2] & 0xFF) << 8)
                    | (src[offset + 3] & 0xFF));
            return value;
        }
        public static byte[] StrToByteArray(string str)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            return encoding.GetBytes(str);
        }

        public static string ByteArrayToStr(byte[] barr)
        {
            System.Text.UnicodeEncoding encoding = new UnicodeEncoding();
            return encoding.GetString(barr);
        }
        #endregion


        private void btnClearLog_Click(object sender, EventArgs e)
        {
            ClearLog();
        }

        private void btnGetVersion_Click(object sender, EventArgs e)
        {
            try
            {
                //端口判断
                int nPort = GetReaderPortNo();
                if (nPort == 0)
                {
                    WriteErrorLog("请先设置读卡器端口");
                    return;
                }

                int nRet = IDCardReader.InitComm((ReaderPortNum)nPort);
                if (nRet != 0)
                {
                    WriteErrorLog("读卡器初始化错误，请检查是否插了设备");
                    return;
                }
                rpNum = (ReaderPortNum)nPort;
                ButtonEnabled(true);
                btnLoopTest.Enabled = true;
                UpdateLoopTestMessage("读取成功，固件版本信息：" + IDCardReader.GetFwVersion());
            }
            catch { ButtonEnabled(false); }
            finally
            {
                IDCardReader.CloseComm();
            }
        }

        private void ICCardTransmite(ReaderSlotNum nSlot, string cmd)
        {
            byte[] bySendData;
            byte[] byRecvData = new byte[200];
            int nLen = 0;
            int nRet = -1;
            string sResp = "";
            string sMsg = "";
            nRet = IDCardReader.ISO7816_CardInsert(nSlot);
            if (nRet != 0)
            {
                WriteErrorLog("未插卡");
                return;
            }

            bySendData = Utils.StrToHexByte(cmd);
            nRet = IDCardReader.ISO7816_TransApdu(nSlot, bySendData, bySendData.Length, byRecvData, ref nLen);

            if (nRet != 0)
            {
                WriteErrorLog("APDU命令错误,错误代码[" + nRet + "]");
                return;
            }

            sResp = Utils.HexByteToStr(byRecvData, nLen);

            if (nSlot == ReaderSlotNum.SmartCard)
                sMsg += "IC";
            else
                sMsg += "PSAM";
            sMsg += "_APDU:[" + textBox2.Text + "]"
                + System.Environment.NewLine
                + "RESP:["
                + sResp.Trim() + "]"
                + System.Environment.NewLine;
            WriteLog(sMsg);
        }

        private void btnResetCard_Click(object sender, EventArgs e)
        {
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                string sCardInfo;
                byte[] byRecvData = new byte[200];
                int nLen = 0;
                int nRet = -1;
                byte byAnt = 0;

                //非接卡
                if (chkSwitchAnt.Checked)
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, ref byAnt, byRecvData, ref nLen);
                else
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, byRecvData, ref nLen);
                if (nRet == 0)
                {
                    if (byRecvData[0] == 0x0a || byRecvData[0] == 0x0b)
                    {
                        sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                        if (chkSwitchAnt.Checked)
                            WriteLog("天线" + byAnt + "非接卡，复位信息:[" + sCardInfo.Trim() + "]");
                        else
                            WriteLog("非接卡，复位信息:[" + sCardInfo.Trim() + "]");
                        if (chkBeep.Checked) BeepOne();
                        return;
                    }
                    else if (byRecvData[0] == 0x0f)
                    {
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.DN, byRecvData, ref nLen);
                        if (nRet == 0)
                        {
                            sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                            WriteLog("身份证，DN信息:[" + sCardInfo.Trim() + "]");
                            if (chkBeep.Checked) BeepOne();
                            return;
                        }
                    }                    
                }
                //接触卡
                nRet = IDCardReader.ISO7816_CardInsert(ReaderSlotNum.SmartCard);
                if (nRet == 0)
                {
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.SmartCard, byRecvData, ref nLen);
                    if (nRet == 0)
                    {
                        sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                        WriteLog("大卡座，复位信息:[" + sCardInfo.Trim() + "]");
                        if (chkBeep.Checked) BeepOne();
                        return;
                    }
                }
                else
                {
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.PsamCard, byRecvData, ref nLen);
                    if (nRet == 0)
                    {
                        sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                        WriteLog("PSAM座，复位信息:[" + sCardInfo.Trim() + "]");
                        if (chkBeep.Checked) BeepOne();
                        return;
                    }
                }
                //M1卡
                if (chkSwitchAnt.Checked)
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.Mifare1, ref byAnt, byRecvData, ref nLen);
                else
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.Mifare1, byRecvData, ref nLen);
                if (nRet == 0)
                {
                    WriteLog("M1卡，卡号:[" + bytesToInt(byRecvData, 0) + "],HEX:[" +
                        string.Format("{0:X2}", byRecvData[0]) + string.Format("{0:X2}", byRecvData[1]) +
                        string.Format("{0:X2}", byRecvData[2]) + string.Format("{0:X2}", byRecvData[3]) + "]");
                    if (chkBeep.Checked) BeepOne();
                    return;
                }

                //15693
                if (chkSwitchAnt.Checked)
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.ISO15693, ref byAnt, byRecvData, ref nLen);
                else
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.ISO15693, byRecvData, ref nLen);
                if (nRet == 0)
                {
                    sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                    if (chkSwitchAnt.Checked)
                        WriteLog("天线" + byAnt + "15693，复位信息:[" + sCardInfo.Trim() + "]");
                    else
                        WriteLog("15693，复位信息:[" + sCardInfo.Trim() + "]");
                    if (chkBeep.Checked) BeepOne();
                    return;
                }
                else
                    WriteErrorLog("复位卡片出错！");
                return;               
            }
            finally
            {
                IDCardReader.CloseComm();
            }
        }

        private void btnReadSSCard_Click(object sender, EventArgs e)
        {
            byte[] byRecvData = new byte[200];
            //int nLen = 0;
            int nRet = -1, nLen = 0;
            string sResp = "";
            IDCardReader.SSC_INFO info = new IDCardReader.SSC_INFO();
            info.SSSE_EF05 = new byte[100];
            info.SSSE_EF06 = new byte[100];
            info.SSSE_EF07 = new byte[300];
            ReaderSlotNum readerSlot;
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                nRet = IDCardReader.ISO7816_CardInsert(ReaderSlotNum.SmartCard);
                if (nRet != 0)
                {
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.TypeA, byRecvData, ref nLen);
                    if (nRet != 0)
                    {
                        MessageBox.Show("请插入社保卡");
                        return;
                    }
                    readerSlot = ReaderSlotNum.TypeA;
                }
                else
                {
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.SmartCard, byRecvData, ref nLen);
                    if (nRet != 0)
                    {
                        MessageBox.Show("请插入社保卡");
                        return;
                    }
                    readerSlot = ReaderSlotNum.SmartCard;
                }

                nRet = IDCardReader.SSC_Authentication(readerSlot);
                if (nRet != 0 && nRet != -55)//三代社保卡无PSAM时返回-55
                {
                    WriteLog("读取社保卡错误,错误代码[" + nRet + "]");
                    return;
                }

                nRet = IDCardReader.SSC_Read_Content(readerSlot, ref info);
                if (nRet != 0)
                {
                    WriteLog("读取社保卡错误,错误代码[" + nRet + "]");
                    return;
                }
                if (info.SSSE_EF05_Len > 0 && info.SSSE_EF06_Len > 0)
                {
                    sResp = Utils.HexByteToStr(info.SSSE_EF05, (int)info.SSSE_EF05_Len);
                    List<TLV> data1 = TLVHelper.ToTLVEntityList(sResp);

                    sResp = Utils.HexByteToStr(info.SSSE_EF06, (int)info.SSSE_EF06_Len);
                    data1.AddRange(TLVHelper.ToTLVEntityList(sResp));

                    TLV CardNum = TLVHelper.GetValueByTag(data1, "07");
                    TLV IDNum = TLVHelper.GetValueByTag(data1, "08");
                    TLV Name = TLVHelper.GetValueByTag(data1, "09");
                    WriteLog("卡号：" + Encoding.GetEncoding("GB2312").GetString(CardNum.Value, 0, CardNum.Length[0]));
                    WriteLog("证件号:" + Encoding.GetEncoding("GB2312").GetString(IDNum.Value, 0, IDNum.Length[0]));
                    foreach (var d in Name.Value) if (d.Equals(0)) Name.Length[0]--;
                    WriteLog("姓名:" + Encoding.GetEncoding("GB2312").GetString(Name.Value, 0, Name.Length[0]));
                }
            }
            catch { }
            finally { IDCardReader.CloseComm(); }
        }

        private void btnBankCard_Click(object sender, EventArgs e)
        {
            byte[] byRecvData = new byte[512];
            int nLen = 0;
            int nRet = -1;
            byte byAnt = 0;
            IDCardReader.BC_INFO info = new IDCardReader.BC_INFO();
            info.DG0101 = new byte[260];
            info.DG0102 = new byte[260];
            info.DG0201 = new byte[260];

            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                WriteLog("请放银行卡(等待5秒)！");
                Stopwatch sw = new Stopwatch();
                sw.Start();
                while (true)
                {
                    if (chkSwitchAnt.Checked)
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, ref byAnt, byRecvData, ref nLen);
                    else
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, byRecvData, ref nLen);
                    if (nRet == 0)
                    {
                        break;
                    }
                    else if (sw.Elapsed.Seconds == 5)
                    {
                        WriteErrorLog("未检测到银行卡！");
                        return;
                    }
                    else Thread.Sleep(300);
                }

                nRet = IDCardReader.BC_Read_Content(ref info);
                if (nRet != 0)
                {
                    WriteLog("读取银行卡错误,错误代码[" + nRet + "]");
                    return;
                }

                WriteLog("卡号：" + info.ICCardNo);
                WriteLog("有效期：20" + info.ValidThru);
               
            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }

        private void btnReadEID_Click(object sender, EventArgs e)
        {
            byte[] byRecvData = new byte[512];
            byte[] byEIDSn = new byte[16];
            int nLen = 0;
            int nRet = -1;
            //string sResp = "";
            byte byAnt = 0;
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                WriteLog("请放卡(等待5秒)！");
                Stopwatch sw = new Stopwatch();
                sw.Start();
                while (true)
                {
                    if (chkSwitchAnt.Checked)
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.TypeA, ref byAnt, byRecvData, ref nLen);
                    else
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.TypeA, byRecvData, ref nLen);
                    if (nRet == 0)
                    {
                        break;
                    }
                    else if (sw.Elapsed.Seconds == 5)
                    {
                        WriteErrorLog("未检测到卡！");
                        return;
                    }
                    else Thread.Sleep(300);
                }

                nRet = IDCardReader.EID_Authentication(byEIDSn);
                if (nRet != 0)
                {
                    WriteErrorLog("卡片认证失败，请重新放卡！");
                    return;
                }

                nRet = IDCardReader.EID_Read_Content(byEIDSn);
                if (nRet != 0)
                {
                    if (nRet == -55) MessageBox.Show("请将PSAM卡插入卡座板，并连接好卡座板！");
                    WriteErrorLog("读取证件信息错误，请重新放卡！");
                    return;
                }
                DispIDInfo();
                WriteLog("读取电子身份证信息成功！");                
            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }

        private void btnReadIDCard_Click(object sender, EventArgs e)
        {
            byte[] byRecvData = new byte[512];
            byte[] byEIDSn = new byte[16];
            int nLen = 0;
            int nRet = -1;
            //string sResp = "";
            byte byAnt = 0;
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }

                WriteLog("请放身份证(等待5秒)！");
                Stopwatch sw = new Stopwatch();
                sw.Start();
                while (true)
                {
                    if (chkSwitchAnt.Checked)
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, ref byAnt, byRecvData, ref nLen);
                    else
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, byRecvData, ref nLen);
                    if (nRet == 0 && byRecvData[0] == 0x0f)
                    {
                        break;
                    }
                    else if (sw.Elapsed.Seconds == 5)
                    {
                        PlayError(8);
                        WriteErrorLog("未检测到身份证！");
                        return;
                    }
                    else Thread.Sleep(300);
                }
                sw.Restart();
                IDCardReader.Authenticate();
                int readContent = IDCardReader.Read_Content(1);
                sw.Stop();
                if (readContent != 0)
                {
                    WriteErrorLog("读取身份证信息出错！");
                    PlayError(3);
                    return;
                }

                DispIDInfo();
                WriteLog("读取身份证信息成功！");
                WriteLog(string.Format("用时：{0:D2}s{1:D3}ms", sw.Elapsed.Seconds, sw.Elapsed.Milliseconds));
                PlayOK();
            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }

        private void DispIDInfo()
        {
            if (IDCardReader.IsFPRIDCard() == 1)
            {
                WriteLog("外国人永久居留证");
                byte[] arrTmp = new byte[100];
                int nLen = 100;
                //姓名
                IDCardReader.GetFPR_ENName(arrTmp, ref nLen);
                string str = System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                WriteLog(str.Replace(" ", ""));
                //中文姓名
                IDCardReader.GetFPR_CHNName(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //证件号码
                IDCardReader.GetFPR_IDNo(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //性别
                IDCardReader.GetFPR_SEX(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //国籍                    
                IDCardReader.GetFPR_Nation(arrTmp, ref nLen);
                string nation = System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                IDCardReader.GetFPR_NationCode(arrTmp, ref nLen);
                nation += "/" + System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                WriteLog(nation);
                //出生日期
                IDCardReader.GetFPR_Birthday(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //签发时间
                string stardate;
                IDCardReader.GetFPR_ValidStartDate(arrTmp, ref nLen);
                stardate = System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                stardate += "至";
                //终止时间
                IDCardReader.GetFPR_ValidEndDate(arrTmp, ref nLen);
                stardate += System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                WriteLog(stardate);
            }
            else if (IDCardReader.IsGATIDCard() == 1)
            {
                WriteLog("港澳台居民居住证");
                byte[] arrTmp = new byte[100];
                int nLen = 100;
                //详细地址
                IDCardReader.GetGAT_Address(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //性别
                IDCardReader.GetGAT_SEX(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //通行证号码
                IDCardReader.GetGAT_PassportNo(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //签发机关
                IDCardReader.GetGAT_IssuingAuthority(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //公民身份证号码
                IDCardReader.GetGAT_IDNo(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //姓名
                IDCardReader.GetGAT_Name(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //签发次数
                IDCardReader.GetGAT_IssuanceCount(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));


                IDCardReader.GetGAT_ValidStartDate(arrTmp, ref nLen);
                string startdate = System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                startdate += "至";
                IDCardReader.GetGAT_ValidEndDate(arrTmp, ref nLen);
                startdate += System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                WriteLog(startdate);

                //指纹信息
                bool flag = false;
                byte[] arrFinger = new byte[1024];
                int fingerLen = 100;
                flag = IDCardReader.GetFingerPrint(arrFinger, ref fingerLen);
                if (flag)
                {
                    WriteLog("已获取指纹");

                }
                else
                {
                    WriteLog("无指纹信息");
                }
            }
            else if (IDCardReader.IsFPR2IDCard() == 1)
            {
                WriteLog("新版外国人永久居留证");

                byte[] arrTmp = new byte[100];
                int nLen = 100;

                //姓名
                IDCardReader.GetFPR2_ENName(arrTmp, ref nLen);
                string str = System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                IDCardReader.GetFPR2_ENNameB(arrTmp, ref nLen);
                str += System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                WriteLog(str.Replace(" ", ""));
                //中文姓名
                IDCardReader.GetFPR2_CHNName(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //证件号码
                IDCardReader.GetFPR2_IDNo(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //性别
                IDCardReader.GetFPR2_Sex(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //国籍                    
                IDCardReader.GetFPR2_Nation(arrTmp, ref nLen);
                string nation = System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                IDCardReader.GetFPR2_NationCode(arrTmp, ref nLen);
                nation += "/" + System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                WriteLog(nation);

                //出生日期
                IDCardReader.GetFPR2_Birthday(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
                //签发时间
                IDCardReader.GetFPR2_ValidStartDate(arrTmp, ref nLen);
                string startdate = System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                startdate += "至";
                //终止时间
                IDCardReader.GetFPR2_ValidEndDate(arrTmp, ref nLen);
                startdate += System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                WriteLog(startdate);

                //换证次数
                IDCardReader.GetFPR2_RenewalTimes(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));
            }
            else
            {
                WriteLog("中华人民共和国居民身份证");
                byte[] arrTmp = new byte[100];
                int nLen = 100;

                IDCardReader.GetAddress(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));

                IDCardReader.GetSex(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));

                IDCardReader.GetBornDate(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));

                IDCardReader.GetSignGov(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));

                IDCardReader.GetIDNo(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));

                IDCardReader.GetName(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));

                IDCardReader.GetNation(arrTmp, ref nLen);
                WriteLog(System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen));

                IDCardReader.GetStartDate(arrTmp, ref nLen);
                string startdate = System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                startdate += "至";
                IDCardReader.GetEndDate(arrTmp, ref nLen);
                startdate += System.Text.Encoding.GetEncoding("GB2312").GetString(arrTmp, 0, nLen);
                WriteLog(startdate);

                //指纹信息
                Boolean flag = false;
                byte[] arrFinger = new byte[1024];
                int fingerLen = 100;
                flag = IDCardReader.GetFingerPrint(arrFinger, ref fingerLen);
                if (flag)
                {
                    WriteLog("已获取指纹");
                }
                else
                {
                    WriteLog("无指纹信息");
                }
            }
            if (System.IO.File.Exists(Application.StartupPath + @"\ZP.bmp"))
            {
                picPhoto.Visible = true;
                picPhoto.ImageLocation = Application.StartupPath + @"\zp.bmp";
            } else picPhoto.Visible = false;
        }

        private void cmbReaderPort_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmbPortNo.Items.Clear();
            string type = this.cmbReaderPort.Text;
            switch (type)
            {
                case "":
                    MessageBox.Show("请选择类型");
                    break;
                case "COM":
                    this.cmbPortNo.Items.AddRange(new object[] {
                    "COM-1",
                    "COM-2",
                    "COM-3",
                    "COM-4",
                    "COM-5","COM-6","COM-7","COM-8"});
                    this.cmbPortNo.SelectedIndex = 0;
                    break;
                case "USB":
                    this.cmbPortNo.Items.AddRange(new object[] {
                    "USB",
                    });
                    this.cmbPortNo.SelectedIndex = 0;
                    break;
                default:
                    break;
            }
        }

        private int GetReaderPortNo()
        {
            string type = cmbReaderPort.Text;
            switch (type)
            {
                case "":
                    return 0;
                case "COM":
                    string no = cmbPortNo.Text;
                    switch (no)
                    {
                        case "COM-1": return 2501;
                        case "COM-2": return 2502;
                        case "COM-3": return 2503;
                        case "COM-4": return 2504;
                        case "COM-5": return 2505;
                        case "COM-6": return 2506;
                        case "COM-7": return 2507;
                        case "COM-8": return 2508;
                    }
                    break;
                case "USB":
                    return 2401;
                default:
                    break;
            }
            return 0;
        }

        private void chkSwitchAnt_CheckedChanged(object sender, EventArgs e)
        {
            int nRet;

            try
            {
                //端口判断
                int nPort = GetReaderPortNo();
                if (nPort == 0)
                {
                    MessageBox.Show("请先设置读卡器端口");
                    return;
                }

                nRet = IDCardReader.InitComm((ReaderPortNum)nPort);
                if (nRet != 0)
                {
                    MessageBox.Show("读卡器初始化错误，请检查是否插了设备");
                    return;
                }
                if (chkSwitchAnt.Checked)
                {
                    nRet = IDCardReader.SetAntPower(0x12);
                    if (nRet != 0)
                        WriteLog("切换天线2失败！" + nRet);
                }
                else
                {
                    nRet = IDCardReader.SetAntPower(0x02);
                    if (nRet != 0)
                        WriteLog("切换天线1失败！" + nRet);
                }
            }
            catch { }
            finally
            {
                IDCardReader.CloseComm();
            }
        }

        private void btnJMJ_Click(object sender, EventArgs e)
        {
            try
            {
                jmj formJmj = new jmj();
                formJmj.ShowDialog();
            }
            catch { }
        }

        #region 15693
        private void btn15693ResetCard_Click(object sender, EventArgs e)
        {
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                byte[] byRecvData = new byte[200];
                int nLen = 0;
                int nRet = IDCardReader.ActivateCard(ReaderSlotNum.ISO15693, byRecvData, ref nLen);
                if (nRet != 0)
                {
                    WriteLog("未寻到标签！");
                    return;
                }
                string sUID = Utils.HexByteToStr(byRecvData, nLen);
                WriteLog("15693标签复位成功:UID[" + sUID + "]");
                txtTag.Text = sUID;
            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }

        private void btn15693ReadBlock_Click(object sender, EventArgs e)
        {           
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                byte[] byRecvData = new byte[200];
                int nRet = -1;

                int numOfBlksRead = int.Parse(cmbBlockNum.Text);
                int addrOfBlkRead = int.Parse(udAddress.Value.ToString());
                byte[] bufBlockDat = new byte[numOfBlksRead * 4];
                int bytesBlkDatRead = 0;
                nRet = IDCardReader.ISO15693_ReadMultiBlocks(false, addrOfBlkRead, numOfBlksRead, ref numOfBlksRead, bufBlockDat, bufBlockDat.Length, ref bytesBlkDatRead);
                if (nRet != 0)
                {
                    WriteLog("读数据出错,请重新复位卡片！");
                    return;
                }
                string sReadData = Utils.HexByteToStr(bufBlockDat, bytesBlkDatRead);
                WriteLog("15693标签读数据成功:[" + sReadData + "]");
                PlayOK();

            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }

        private void btn15693WriteBlock_Click(object sender, EventArgs e)
        {
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                int numOfBlksWrite = int.Parse(cmbBlockNum.Text);
                int addrOfBlkWrite = int.Parse(udAddress.Value.ToString());
                byte[] newBlkData = new byte[numOfBlksWrite * 4];
                byte[] tmpData = System.Text.Encoding.ASCII.GetBytes(txtWriteInfo.Text);
                for (int i = 0; i < tmpData.Length; i++) newBlkData[i] = tmpData[i];
                int nRet = IDCardReader.ISO15693_WriteMultipleBlocks(5, 2, newBlkData, newBlkData.Length);
                if (nRet != 0)
                {
                    WriteErrorLog("15693标签写数据出错[" + nRet.ToString() + "]");
                }
                else
                {
                    WriteLog("15693标签写数据成功:[" + Utils.HexByteToStr(newBlkData, newBlkData.Length) + "]");
                    PlayOK();
                }
            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
            
        }
        #endregion
        
        #region 电子护照
        private void btnEPResetCard_Click(object sender, EventArgs e)
        {
            int nRet, nLen = 0;
            byte byAnt = 0;
            byte[] byRecvData = new byte[512];
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }

                WriteLog("请放卡(等待5秒)！");
                Stopwatch sw = new Stopwatch();
                sw.Start();
                while (true)
                {
                    if (chkSwitchAnt.Checked)
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, ref byAnt, byRecvData, ref nLen);
                    else
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, byRecvData, ref nLen);
                    if (nRet == 0 && byRecvData[0] != 0x0f)
                    {
                        break;
                    }
                    else if (sw.Elapsed.Seconds == 5)
                    {
                        WriteErrorLog("未检测到卡！");
                        return;
                    }
                    else Thread.Sleep(300);
                }
                WriteLog("检测到证件...");
                PlayOK();
            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }
        
        private void btnReadMRTD_Click(object sender, EventArgs e)
        {
            int nRet = -1;
            string sEppNo = "", sDateOfBorn = "", sDateOfExpiry = "";
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }

                if (mtxtDocNo.Text.Replace(" ", "").Length < 5)
                {
                    WriteLog("证件号码长度不正确");
                    return;
                }
                sEppNo = mtxtDocNo.Text.Replace(" ", "");
                while (sEppNo.Length < 9) sEppNo += "<";
                sDateOfBorn = dtpDateOfBorn.Value.Date.ToString("yyMMdd");
                sDateOfExpiry = dtpDateOfExpiry.Value.Date.ToString("yyMMdd");


                Stopwatch sw = new Stopwatch();

                WriteLog("开始认证...");
                sw.Start();

                nRet = IDCardReader.EPP_Authentication(sEppNo, sDateOfBorn, sDateOfExpiry);
                if (nRet != 0)
                {
                    WriteErrorLog("证件认证失败(" + nRet + ")，请检查输入信息是否正确。");
                    return;
                }
                WriteLog("开始读取电子信息...");
                int nType = 2;
                if (chkReadDG2.Checked)
                    nType = 1;
                nRet = IDCardReader.EPP_Read_Content(nType);
                sw.Stop();
                if (nRet != 0)
                {
                    WriteErrorLog("读取电子信息失败，请拿开证件重新操作。");
                    return;
                }
                IDCardReader.EPP_Info info = new IDCardReader.EPP_Info();
                nRet = IDCardReader.EPP_GetInfo(ref info);
                if (nRet != 0)
                {
                    WriteErrorLog("解析电子信息失败。");
                    return;
                }
                WriteLog(IDCardReader.EPP_Parse_DocumentType(info.DocumentType));
                WriteLog(info.DocumentNumber);
                WriteLog(info.Name);
                WriteLog(info.CustName);
                WriteLog(info.DateOfBorn);
                WriteLog(info.DateOfIssue);
                WriteLog(info.DateOfExpiry);
                WriteLog(info.Gender);
                WriteLog(info.NationalityIso);
                WriteLog(info.CustNo);
                WriteLog(info.IssuingCountryIso);
                WriteLog(info.Address);
                WriteLog(info.MRZ1);
                WriteLog(info.MRZ2);
                WriteLog(info.MRZ3);
                if (File.Exists(info.PhotoName))
                {
                    picPhoto.Image = Image.FromFile(info.PhotoName);
                    picPhoto.Visible = true;
                } else picPhoto.Visible = false;
                WriteLog("读取完成...");
                WriteLog(string.Format("用时：{0:D2}s{1:D3}ms", sw.Elapsed.Seconds, sw.Elapsed.Milliseconds));
                if (chkBeep.Checked) BeepOne();
            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }
        #endregion

        #region M1卡
        private void btnM1ResetCard_Click(object sender, EventArgs e)
        {
            byte[] byRecvData = new byte[200];
            int nLen = 0;
            int nRet = -1;
            byte byAnt = 0;

            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                //M1卡
                if (chkSwitchAnt.Checked)
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.Mifare1, ref byAnt, byRecvData, ref nLen);
                else
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.Mifare1, byRecvData, ref nLen);
                if (nRet == 0)
                {
                    WriteLog("M1卡，卡号:[" + bytesToInt(byRecvData, 0) + "],HEX:[" +
                        string.Format("{0:X2}", byRecvData[0]) + string.Format("{0:X2}", byRecvData[1]) +
                        string.Format("{0:X2}", byRecvData[2]) + string.Format("{0:X2}", byRecvData[3]) + "]");
                    if (chkBeep.Checked) BeepOne();
                    return;
                }
            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }

        private void btnM1ReadHex_Click(object sender, EventArgs e)
        {
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }

                byte[] byRecvData = new byte[200];
                int nLen = 0;
                int nRet = -1;
                byte byAnt = 0;
                if (chkSwitchAnt.Checked)
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.Mifare1, ref byAnt, byRecvData, ref nLen);
                else
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.Mifare1, byRecvData, ref nLen);

                if (nRet != 0)
                {
                    WriteLog("复位卡片出错！");
                    return;
                }

                byte[] keyA = null;
                byte[] keyB = null;
                byte sector = 0;
                int block = 0;
                sector = byte.Parse(cmbM1Sector.Text);
                block = sector * 4 + byte.Parse(cmbM1Block.Text);                

                if (rdbKeyA.Checked)
                    keyA = Utils.StrToHexByte(txtM1Key.Text);
                else
                    keyB = Utils.StrToHexByte(txtM1Key.Text);

                nRet = IDCardReader.MIFARE_Authentication(sector, keyA, keyB);
                if (nRet != 0)
                {
                    WriteErrorLog("认证M1卡片错误");
                    return;
                }
                nRet = IDCardReader.MIFARE_ReadData((byte)block, byRecvData, 16);
                if (nRet != 0)
                {
                    WriteErrorLog("读取块数据错误");
                    return;
                }
                WriteLog("块数据读取成功:[" + Utils.HexByteToStr(byRecvData, 16) + "]");
            }
            catch { }
            finally
            {
                if (chkAntPower.Checked)
                    IDCardReader.SetAntPower(0);
                IDCardReader.CloseComm();
            }
        }

        private void btnM1ReadASC_Click(object sender, EventArgs e)
        {
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }

            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }

        private void btnM1WriteHex_Click(object sender, EventArgs e)
        {
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }

                byte[] byRecvData = new byte[200];
                int nLen = 0;
                int nRet = -1;
                byte byAnt = 0;
                if (chkSwitchAnt.Checked)
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.Mifare1, ref byAnt, byRecvData, ref nLen);
                else
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.Mifare1, byRecvData, ref nLen);

                if (nRet != 0)
                {
                    WriteLog("复位卡片出错！");
                    return;
                }

                byte[] keyA = null;
                byte[] keyB = null;
                byte sector = 0;
                int block = 0;
                sector = byte.Parse(cmbM1Sector.Text);
                block = sector * 4 + byte.Parse(cmbM1Block.Text);
                byte[] writeData = Utils.StrToHexByte(txtM1Data.Text);

                if (rdbKeyA.Checked)
                    keyA = Utils.StrToHexByte(txtM1Key.Text);
                else
                    keyB = Utils.StrToHexByte(txtM1Key.Text);

                nRet = IDCardReader.MIFARE_Authentication(sector, keyA, keyB);
                if (nRet != 0)
                {
                    WriteErrorLog("认证M1卡片错误");
                    return;
                }
                nRet = IDCardReader.MIFARE_WrtieData((byte)block, writeData, 16);
                if (nRet != 0)
                {
                    WriteLog("写入块数据错误");
                    return;
                }                
                WriteLog("块数据写入成功:[" + Utils.HexByteToStr(writeData, 16) + "]");
            }
            catch { }
            finally
            {
                if (chkAntPower.Checked)
                    IDCardReader.SetAntPower(0);
                IDCardReader.CloseComm();
            }
        }

        private void btnM1WriteASC_Click(object sender, EventArgs e)
        {
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }

            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }
        #endregion

        #region 智能卡
        private void btnSCResetCard_Click(object sender, EventArgs e)
        {
            string sCardInfo;
            byte[] byRecvData = new byte[200];
            int nLen = 0;
            int nRet = -1;
            byte byAnt = 0;
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteErrorLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                if (cmbSCardType.SelectedIndex == 0)
                {
                    //非接卡
                    if (chkSwitchAnt.Checked)
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, ref byAnt, byRecvData, ref nLen);
                    else
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, byRecvData, ref nLen);
                    if (nRet == 0)
                    {
                        if (byRecvData[0] == 0x0a || byRecvData[0] == 0x0b)
                        {
                            sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                            if (chkSwitchAnt.Checked)
                                WriteLog("天线" + byAnt + "非接卡，复位信息:[" + sCardInfo.Trim() + "]");
                            else
                                WriteLog("非接卡，复位信息:[" + sCardInfo.Trim() + "]");
                            if (chkBeep.Checked) BeepOne();
                            return;
                        }
                        else
                        {
                            WriteErrorLog("不支持的卡!");
                            return;
                        }
                    }
                }
                else if (cmbSCardType.SelectedIndex == 1)
                {
                    //接触卡
                    nRet = IDCardReader.ISO7816_CardInsert(ReaderSlotNum.SmartCard);
                    if (nRet == 0)
                    {
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.SmartCard, byRecvData, ref nLen);
                        if (nRet == 0)
                        {
                            sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                            WriteLog("大卡座，复位信息:[" + sCardInfo.Trim() + "]");
                            if (chkBeep.Checked) BeepOne();
                            return;
                        }
                    }
                    else
                    {
                        WriteErrorLog("大卡座上电错误!");
                        return;
                    }
                }
                else if (cmbSCardType.SelectedIndex == 2)
                {
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.PsamCard, byRecvData, ref nLen);
                    if (nRet == 0)
                    {
                        sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                        WriteLog("PSAM卡座，复位信息:[" + sCardInfo.Trim() + "]");
                        if (chkBeep.Checked) BeepOne();
                        return;
                    }
                    else
                    {
                        WriteErrorLog("PSAM卡座上电错误!");
                        return;
                    }
                }
            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }

        private void btnSCTransCmd_Click(object sender, EventArgs e)
        {
            string sResp = "";
            bool bRet = false;
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteErrorLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                string msg;
                if (chkSystem.Checked)
                {
                    if (cmbSCardType.SelectedIndex == 1)//IC卡座
                    {
                        bRet = IDCardReader.TransCommand(ReaderSlotNum.SmartCard, textBox2.Text, out sResp);
                        msg = "IC";
                    }
                    else if (cmbSCardType.SelectedIndex == 2)//PSAM卡座
                    {
                        bRet = IDCardReader.TransCommand(ReaderSlotNum.PsamCard, textBox2.Text, out sResp);
                        msg = "PSAM";
                    }
                    else
                    {
                        bRet = IDCardReader.TransCommand(0, textBox2.Text, out sResp);
                        msg = "RF";
                    }
                    if (!bRet)
                    {
                        msg += "_APDU命令错误,错误代码[" + sResp + "]";
                        WriteErrorLog(msg);
                        return;
                    }
                    msg += "_APDU:[" + textBox2.Text + "]" + Environment.NewLine + "返回:[" + sResp.Trim() + "]";
                    WriteLog(msg);
                    PlayOK();
                    return;
                }
                else
                {
                    if (cmbSCardType.SelectedIndex == 0)
                    {
                        bRet = IDCardReader.TransApdu(ReaderSlotNum.RFDCard, textBox2.Text, out sResp);
                    }
                    else if (cmbSCardType.SelectedIndex == 1)//IC卡座
                    {
                        ICCardTransmite(ReaderSlotNum.SmartCard, textBox2.Text);
                        return;
                    }
                    else if (cmbSCardType.SelectedIndex == 2)//PSAM卡座
                    {
                        ICCardTransmite(ReaderSlotNum.PsamCard, textBox2.Text);
                        return;
                    }
                    if (!bRet)
                    {
                        WriteErrorLog("APDU命令错误,错误代码[" + sResp + "]");
                        return;
                    }
                    WriteLog("执行命令[" + textBox2.Text + "],返回:[" + sResp.Trim() + "]");
                    PlayOK();
                }
            }
            finally
            {
                IDCardReader.CloseComm();
            }
        }

        private void btnSCPowerdown_Click(object sender, EventArgs e)
        {
            try
            {
                if (IDCardReader.InitComm(rpNum) != 0)
                {
                    WriteLog("打开读卡器出错！");
                    PlayError(0);
                    return;
                }
                if(cmbSCardType.SelectedIndex == 0)
                    IDCardReader.SetAntPower(0);
                else if (cmbSCardType.SelectedIndex == 1)
                    IDCardReader.ISO7816_CardRemove(ReaderSlotNum.SmartCard);
                else if (cmbSCardType.SelectedIndex == 2)
                    IDCardReader.ISO7816_CardRemove(ReaderSlotNum.PsamCard);
                WriteLog("卡下电操作完成.");
            }
            catch (Exception exp) { MessageBox.Show(exp.Message); }
            finally { IDCardReader.CloseComm(); }
        }
        #endregion

        #region 循环测试
        bool[] btnStatus = new bool[20];
        private void ButtonEnabled(bool en)
        {
            int nPtr = 0;
            if (en)
            {
                btnResetCard.Enabled = btnStatus[nPtr++];
                btnSCTransCmd.Enabled = btnStatus[nPtr++];
                btnReadSSSE.Enabled = btnStatus[nPtr++];
                btnBankCard.Enabled = btnStatus[nPtr++];
                btnReadEID.Enabled = btnStatus[nPtr++];
                btnReadMRTD.Enabled = btnStatus[nPtr++];
                btnReadIDCard.Enabled = btnStatus[nPtr++];
                btnJMJ.Enabled = btnStatus[nPtr++];

                btn15693ResetCard.Enabled = btnStatus[nPtr++];
                btn15693ReadBlock.Enabled = btnStatus[nPtr++];
                btn15693WriteBlock.Enabled = btnStatus[nPtr++];
                btnEPResetCard.Enabled = btnStatus[nPtr++];
                btnM1ResetCard.Enabled = btnStatus[nPtr++];
                btnM1ReadASC.Enabled = btnStatus[nPtr++];
                btnM1ReadHex.Enabled = btnStatus[nPtr++];
                btnM1WriteASC.Enabled = btnStatus[nPtr++];
                btnM1WriteHex.Enabled = btnStatus[nPtr++];
                btnSCResetCard.Enabled = btnStatus[nPtr++];
                btnSCPowerdown.Enabled = btnStatus[nPtr++];
                //btnLoopTest.Enabled = btnStatus[nPtr++];
            }
            else
            {
                btnStatus[nPtr++] = btnResetCard.Enabled;
                btnStatus[nPtr++] = btnSCTransCmd.Enabled;
                btnStatus[nPtr++] = btnReadSSSE.Enabled;
                btnStatus[nPtr++] = btnBankCard.Enabled;
                btnStatus[nPtr++] = btnReadEID.Enabled;
                btnStatus[nPtr++] = btnReadMRTD.Enabled;
                btnStatus[nPtr++] = btnReadIDCard.Enabled;
                btnStatus[nPtr++] = btnJMJ.Enabled;

                btnStatus[nPtr++] = btn15693ResetCard.Enabled;
                btnStatus[nPtr++] = btn15693ReadBlock.Enabled;
                btnStatus[nPtr++] = btn15693WriteBlock.Enabled;
                btnStatus[nPtr++] = btnEPResetCard.Enabled;
                btnStatus[nPtr++] = btnM1ResetCard.Enabled;
                btnStatus[nPtr++] = btnM1ReadASC.Enabled;
                btnStatus[nPtr++] = btnM1ReadHex.Enabled;
                btnStatus[nPtr++] = btnM1WriteASC.Enabled;
                btnStatus[nPtr++] = btnM1WriteHex.Enabled;
                btnStatus[nPtr++] = btnSCResetCard.Enabled;
                btnStatus[nPtr++] = btnSCPowerdown.Enabled;
                //btnStatus[nPtr++] = btnLoopTest.Enabled;

                btnResetCard.Enabled = false;
                btnSCTransCmd.Enabled = false;
                btnReadSSSE.Enabled = false;
                btnBankCard.Enabled = false;
                btnReadEID.Enabled = false;
                btnReadMRTD.Enabled = false;
                btnReadIDCard.Enabled = false;
                btnJMJ.Enabled = false;

                btn15693ResetCard.Enabled = false;
                btn15693ReadBlock.Enabled = false;
                btn15693WriteBlock.Enabled = false;
                btnEPResetCard.Enabled = false;
                btnM1ResetCard.Enabled = false;
                btnM1ReadASC.Enabled = false;
                btnM1ReadHex.Enabled = false;
                btnM1WriteASC.Enabled = false;
                btnM1WriteHex.Enabled = false;
                btnSCResetCard.Enabled = false;
                btnSCPowerdown.Enabled = false;
                //btnLoopTest.Enabled = false;
            }
        }
        private Thread progressThread = null;
        private Stopwatch sw = new Stopwatch();
        private void newProcess()
        {
            try
            {
                string sCardInfo;
                byte[] byRecvData = new byte[200];
                int nLen = 0;
                int nRet = -1;
                byte byAnt = 0;

                //非接卡
                if (chkSwitchAnt.Checked)
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, ref byAnt, byRecvData, ref nLen);
                else
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.RFDCard, byRecvData, ref nLen);
                if (nRet == 0)
                {
                    if (byRecvData[0] == 0x0a || byRecvData[0] == 0x0b)
                    {
                        sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                        if (chkSwitchAnt.Checked)
                            WriteLog("天线" + byAnt + "非接卡，复位信息:[" + sCardInfo.Trim() + "]");
                        else
                            WriteLog("非接卡，复位信息:[" + sCardInfo.Trim() + "]");
                        if (chkBeep.Checked) BeepOne();
                        succ++;
                    }
                    else if (byRecvData[0] == 0x0f)
                    {
                        nRet = IDCardReader.ActivateCard(ReaderSlotNum.DN, byRecvData, ref nLen);
                        if (nRet == 0)
                        {
                            sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                            WriteLog("身份证，DN信息:[" + sCardInfo.Trim() + "]");
                            if (chkBeep.Checked) BeepOne();
                            succ++;
                        }
                    }
                }
                //接触卡
                nRet = IDCardReader.ISO7816_CardInsert(ReaderSlotNum.SmartCard);
                if (nRet == 0)
                {
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.SmartCard, byRecvData, ref nLen);
                    if (nRet == 0)
                    {
                        sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                        WriteLog("大卡座，复位信息:[" + sCardInfo.Trim() + "]");
                        if (chkBeep.Checked) BeepOne();
                        succ++;
                    }
                }
                else
                {
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.PsamCard, byRecvData, ref nLen);
                    if (nRet == 0)
                    {
                        sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                        WriteLog("PSAM座，复位信息:[" + sCardInfo.Trim() + "]");
                        if (chkBeep.Checked) BeepOne();
                        succ++;
                    }
                }
                //M1卡
                if (chkSwitchAnt.Checked)
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.Mifare1, ref byAnt, byRecvData, ref nLen);
                else
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.Mifare1, byRecvData, ref nLen);
                if (nRet == 0)
                {
                    WriteLog("M1卡，卡号:[" + bytesToInt(byRecvData, 0) + "],HEX:[" +
                        string.Format("{0:X2}", byRecvData[0]) + string.Format("{0:X2}", byRecvData[1]) +
                        string.Format("{0:X2}", byRecvData[2]) + string.Format("{0:X2}", byRecvData[3]) + "]");
                    if (chkBeep.Checked) BeepOne();
                    succ++;
                }

                //15693
                if (chkSwitchAnt.Checked)
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.ISO15693, ref byAnt, byRecvData, ref nLen);
                else
                    nRet = IDCardReader.ActivateCard(ReaderSlotNum.ISO15693, byRecvData, ref nLen);
                if (nRet == 0)
                {
                    sCardInfo = Utils.HexByteToStr(byRecvData, nLen);
                    if (chkSwitchAnt.Checked)
                        WriteLog("天线" + byAnt + "15693，复位信息:[" + sCardInfo.Trim() + "]");
                    else
                        WriteLog("15693，复位信息:[" + sCardInfo.Trim() + "]");                    
                    if (chkBeep.Checked) BeepOne();
                    succ++;
                }
            }
            catch { }
            finally
            {
                if (chkAntPower.Checked) IDCardReader.SetAntPower(0);                
                total++;
            }
            UpdateLoopTestMessage("成功：" + succ + "/共：" + total);
        }

        private void loopTestProcess()
        {
            while (true)
            {
                newProcess();
                Thread.Sleep(100);
            }
        }

        private void btnLoopTest_Click(object sender, EventArgs e)
        {
            try
            {
                if (btnLoopTest.Text.Equals("循环测试"))
                {
                    int nPort = GetReaderPortNo();
                    if (nPort == 0)
                    {
                        MessageBox.Show("请先设置读卡器端口");
                        return;
                    }

                    int nRet = IDCardReader.InitComm((ReaderPortNum)nPort);
                    if ((int)nRet == 0)
                    {
                        ButtonEnabled(false);
                        btnLoopTest.Text = "停止";
                        succ = total = 0;

                        if (progressThread == null)
                        {
                            progressThread = new Thread(new ThreadStart(loopTestProcess));
                            progressThread.IsBackground = true;
                        }
                        progressThread.Start();
                        sw.Start();
                    }
                    else
                    {
                        WriteLog("打开失败" + nPort);
                        PlayError(0);
                        return;
                    }
                }
                else
                {
                    ButtonEnabled(true);
                    btnLoopTest.Text = "循环测试";
                    succ = total = 0;
                    if (progressThread != null)
                    {
                        progressThread.Abort();
                        progressThread.Join();
                        progressThread = null;
                    }                    
                    sw.Stop();
                    IDCardReader.CloseComm();
                }
            }
            catch { }
            finally
            {

            }
        }
        #endregion

    }
}
