using CCWin;
using Newtonsoft.Json.Linq;
using SufeiUtil;
using SXLibrary;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System.Text.RegularExpressions;
using System.Diagnostics;
using MOKA_Factory_Tools.BLL;

namespace MOKA_Factory_Tools
{
    public partial class OperationPanel : Skin_Color
    {
        //白平衡URL
        MidList midListNow = new MidList();
        MidList localmidList = new MidList();
        MidAddress MidAddressNow = new MidAddress();
        FunctionSetting FunctionSettingNow = new FunctionSetting();
        WhiteBalanceList WhiteBalanceListNow = new WhiteBalanceList();
        Config_WriteCheck cfg_writecheck = new Config_WriteCheck();
        Config_ReadCheck cfg_readcheck = new Config_ReadCheck();
        Config_WriteDone cfg_writedone = new Config_WriteDone();
        SerialPort TVPort = new SerialPort();
        SQLiteConnection localDBNow;
        SQLiteConnection errorDBNow;
        KeyInfo keyInfo = new KeyInfo();
        FireTVKey fireTVKey = new FireTVKey();
        NTFBLL ntfBLL = null;
        bool preloadNow;
        string SN;
        string orderNow;
        Main mainform;
        int usingTime = 0;
        Thread SNTextFocus;
        bool FocusMark = false;
        Thread WritekeyThread;
        string availableCount = "unknow";
        // 只有NTF才用该变量, 0试产, 1=量产;
        int nOrderType = -1;
        MIKey _MiKey = null;

        //删除界面指针委托
        public delegate void DisplayUpdateDelegate(IntPtr intPtr);
        //删除界面指针事件
        public event DisplayUpdateDelegate DeleteIntptr;

        //扫描回车触发委托
        public delegate void SNKeyDown(IntPtr intPtr);
        //扫描回车触发事件
        public event SNKeyDown SNKeyDownEven;

        //自动key提取委托
        public delegate void AutoKeyRequireDelegate(IntPtr intPtr, string key, string keytype);
        //自动key提取事件
        public event AutoKeyRequireDelegate AutoKeyRequire;

        //定义一个委托  调用Verify窗口;
        delegate void ShowVerifyCallback(string strMsg);

        //委托方法
        private void ShowVerifyDailog(string strMsg)
        {
            //右下角消息框Form
            Verify dlg = new Verify(strMsg);
            dlg.ShowDialog();
        }

        //调用委托
        private void ShowVerifyDelegate(string strMsg)
        {
            //创建委托
            ShowVerifyCallback wt = new ShowVerifyCallback(ShowVerifyDailog);
            //这段代码在主窗体类里面写着，this指主窗体
            this.Invoke(wt, new Object[] { strMsg });
        }

        public OperationPanel(Main form1, SQLiteConnection localDB, SQLiteConnection errorDB, MidAddress midAddress1, FunctionSetting functionSetting, Config_WriteCheck writeCheck1, Config_ReadCheck readCheck1, Config_WriteDone writeDone1, bool preload, MidList midList1, string order)
        {
            InitializeComponent();
            MidAddressNow = midAddress1;
            FunctionSettingNow = functionSetting;
            cfg_writecheck = writeCheck1;
            cfg_readcheck = readCheck1;
            cfg_writedone = writeDone1;
            localDBNow = localDB;
            errorDBNow = errorDB;
            preloadNow = preload;
            midListNow = midList1;
            orderNow = order;
            InitPanel();
            mainform = form1;
            this.mainform.MoveEvent += new MoveHandler(SetFormLocation);
            this.mainform.KeyDownEvent += new KeyDownHandler(SetFocus);
            if (midListNow.rokuCustomer != null)
                ProductMsg_Text.Text = "Roku:";
            if (functionSetting.NTF)
                ntfBLL = new NTFBLL();
        }

        /// <summary>
        /// 控制界面跟随主界面移动
        /// </summary>
        /// <param name="XY"></param>
        /// <param name="formlocationmsg"></param>
        /// <param name="num"></param>
        void SetFormLocation(Point XY, ArrayList formlocationmsg, int num)
        {
            foreach (Dictionary<IntPtr, Point> pairs in formlocationmsg)
            {
                if (!this.IsDisposed)
                {
                    if (pairs.ContainsKey(this.Handle))
                    {
                        if (formlocationmsg.IndexOf(pairs) >= num && num > 0)
                        {
                            this.Left = XY.X + this.Size.Width * (formlocationmsg.IndexOf(pairs) - num);
                            this.Top = XY.Y + this.Size.Height;
                        }

                        else
                        {
                            this.Left = XY.X + this.Size.Width * formlocationmsg.IndexOf(pairs);
                            this.Top = XY.Y;
                        }

                        break;
                    }
                }

            }
        }

        /// <summary>
        /// 按指针设置是否聚焦
        /// </summary>
        /// <param name="formlocationmsg"></param>
        /// <param name="intPtr"></param>
        void SetFocus(ArrayList formlocationmsg, IntPtr intPtr)
        {
            bool mark = false;
            bool mark2 = false;
            foreach (Dictionary<IntPtr, Point> pairs in formlocationmsg)
            {

                if (!this.IsDisposed)
                {
                    if (pairs.ContainsKey(this.Handle) && formlocationmsg.IndexOf(pairs) == 0)
                    {
                        mark2 = true;
                    }
                    if (mark)
                    {
                        if (pairs.ContainsKey(this.Handle))
                            FocusMark = true;
                        else
                            mark = false;
                    }
                    if (pairs.ContainsKey(intPtr))
                    {
                        if (formlocationmsg.IndexOf(pairs) == (formlocationmsg.Count - 1))
                        {
                            if (mark2)
                                FocusMark = true;
                        }
                        mark = true;
                    }
                }

            }
        }

        /// <summary>
        /// 界面控件初始化
        /// </summary>
        public void InitPanel()
        {
            COMText.Text = FunctionSettingNow.TVCOM;
            COMText.BackColor = Color.FromArgb(128, 255, 128);
            BaudText.Text = FunctionSettingNow.TVBaud;
            BaudText.BackColor = Color.FromArgb(128, 255, 128);
            WritePSN.Checked = FunctionSettingNow.BarcodeWrite;

            #region 串口重试机制;
            SerialCMD.EnableRetry = FunctionSettingNow.EnableRetry;
            SerialCMD.RetryCount = FunctionSettingNow.RetryCount;
            #endregion

            #region 设置WriteCheck复选框默认状态;
            if (!cfg_writecheck.DIDCheckcheck)
                SetspecificText(m_checkdid, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.MacCheckcheck)
                SetspecificText(m_checkmac, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.HDCPCheckcheck)
                SetspecificText(m_checkhdcp, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.HDCP22Checkcheck)
                SetspecificText(m_checkhdcp22, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.WidevineCheckcheck)
                SetspecificText(m_checkwidevine, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.ESNCheckcheck)
                SetspecificText(m_checkesn, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.CI_plusCheckcheck)
                SetspecificText(m_checkci, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.AttestationCheckcheck)
                SetspecificText(m_checkattestation, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.MGKCheckcheck)
                SetspecificText(m_checkMGK, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.FairplayCheckcheck)
                SetspecificText(m_checkFairplay, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.ECPCheckcheck)
                SetspecificText(m_checkECP, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.WifiMacCheckcheck)
                SetspecificText(m_checkWifiMac, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.BTMacCheckcheck)
                SetspecificText(m_checkBTMac, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.LEKCheckcheck)
                SetspecificText(m_checkLEK, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.PEKCheckcheck)
                SetspecificText(m_checkPEK, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.PlayreadyCheckcheck)
                SetspecificText(m_checkPlayready, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.HashCheckcheck)
                SetspecificText(m_checkHash, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.DSNCheckcheck)
                SetspecificText(m_checkDSN, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.YouTubeCheckcheck)
                SetspecificText(m_checkYouTube, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.ACASKeyCheckcheck)
                SetspecificText(m_checkACASKey, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.FVPCheckcheck)
                SetspecificText(m_checkFVP, LResource.Skip, Color.Yellow);
            if (!cfg_writecheck.DAKCheckcheck)
                SetspecificText(m_checkDAK, LResource.Skip, Color.Yellow);
            #endregion
            #region 设置ReadCheck复选框默认状态
            /////////////////////////////////////////////////////////////////
            if (!cfg_readcheck.PIDReadcheck)
                SetspecificText(ProjectIDNote, LResource.SkipReadCheck, Color.Yellow);
            if (!cfg_readcheck.DIDReadcheck)
                SetspecificText(m_readdid, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.MacReadcheck)
                SetspecificText(m_readmac, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.HDCPReadcheck)
                SetspecificText(m_readhdcp, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.HDCP22Readcheck)
                SetspecificText(m_readhdcp22, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.WidevineReadcheck)
                SetspecificText(m_readwidevine, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.ESNReadcheck)
                SetspecificText(m_readesn, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.CI_plusReadcheck)
                SetspecificText(m_readci, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.AttestationReadcheck)
                SetspecificText(m_readattestation, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.MGKReadcheck)
                SetspecificText(m_readMGK, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.FairplayReadcheck)
                SetspecificText(m_readFairplay, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.ECPReadcheck)
                SetspecificText(m_readECP, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.WifiMacReadcheck)
                SetspecificText(m_readWifiMac, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.BTMacReadcheck)
                SetspecificText(m_readBTMac, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.LEKReadcheck)
                SetspecificText(m_readLEK, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.PEKReadcheck)
                SetspecificText(m_readPEK, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.PlayreadyReadcheck)
                SetspecificText(m_readPlayready, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.HashReadcheck)
                SetspecificText(m_readHash, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.DSNReadcheck)
                SetspecificText(m_readDSN, LResource.Skip, Color.Yellow);
            if (!cfg_readcheck.SHOPReadcheck)
                SetspecificText(SHOPNote, LResource.SkipChecking, Color.Yellow);
            if (!cfg_readcheck.OSDReadcheck)
                SetspecificText(OSDNote, LResource.SkipChecking, Color.Yellow);
            if (!cfg_readcheck.YouTubeReadcheck)
                SetspecificText(m_readYouTube, LResource.SkipChecking, Color.Yellow);
            if (!cfg_readcheck.EDIDPIDReadcheck)
                SetspecificText(m_readEDIDPID, LResource.SkipChecking, Color.Yellow);
            if (!cfg_readcheck.EDIDModeNameReadcheck)
                SetspecificText(m_readEDIDName, LResource.SkipChecking, Color.Yellow);
            if (!cfg_readcheck.ACASKeyReadcheck)
                SetspecificText(m_readACASKey, LResource.SkipChecking, Color.Yellow);
            if (FunctionSettingNow.ExportSNACASID)
                SetspecificText(m_readACASID, LResource.SkipChecking, Color.Yellow);
            if (!cfg_readcheck.FVPReadcheck)
                SetspecificText(m_readFVP, LResource.SkipChecking, Color.Yellow);
            if (!cfg_readcheck.DAKReadcheck)
                SetspecificText(m_readDAK, LResource.SkipChecking, Color.Yellow);
            #endregion
            #region 设置WriteDone复选框默认状态
            /////////////////////////////////////////////////////////////////
            if (!cfg_writedone.PIDWrite_YesNo)
                SetspecificText(ProjectIDNote, LResource.SkipCovering, Color.Yellow);
            if (!cfg_writedone.ClientTypeCheck_YesNo)
                SetspecificText(ClientTypeNote, LResource.SkipChecking, Color.Yellow);
            if (!cfg_writedone.SoftwareVersionCheck_YesNo)
                SetspecificText(SoftwareVersionNote, LResource.SkipChecking, Color.Yellow);
            if (!cfg_writedone.DIDWrite_YesNo)
                SetspecificText(m_writedid, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.MacWrite_YesNo)
                SetspecificText(m_writemac, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.HDCPWrite_YesNo)
                SetspecificText(m_writehdcp, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.HDCP22Write_YesNo)
                SetspecificText(m_writehdcp22, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.WidevineWrite_YesNo)
                SetspecificText(m_writewidevine, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.ESNWrite_YesNo)
                SetspecificText(m_writeesn, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.CI_plusWrite_YesNo)
                SetspecificText(m_writeci, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.AttestationWrite_YesNo)
                SetspecificText(m_writeattestation, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.MGKWrite_YesNo)
                SetspecificText(m_writeMGK, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.FairplayWrite_YesNo)
                SetspecificText(m_writeFairplay, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.ECPWrite_YesNo)
                SetspecificText(m_writeECP, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.WifiMacWrite_YesNo)
                SetspecificText(m_writeWifiMac, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.BTMacWrite_YesNo)
                SetspecificText(m_writeBTMac, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.LEKWrite_YesNo)
                SetspecificText(m_writeLEK, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.PEKWrite_YesNo)
                SetspecificText(m_writePEK, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.PlayreadyWrite_YesNo)
                SetspecificText(m_writePlayready, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.HashWrite_YesNo)
                SetspecificText(m_writeHash, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.DSNWrite_YesNo)
                SetspecificText(m_writeDSN, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.YouTubeWrite_YesNo)
                SetspecificText(m_writeYouTube, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.EDIDPIDWrite_YesNo)
                SetspecificText(m_writeEDIDPID, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.EDIDModeNameWrite_YesNo)
                SetspecificText(m_writeEDIDName, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.ACASKeyWrite_YesNo)
                SetspecificText(m_writeACASKey, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.FVPWrite_YesNo)
                SetspecificText(m_writeFVP, LResource.Skip, Color.Yellow);
            if (!cfg_writedone.DAKWrite_YesNo)
                SetspecificText(m_writeDAK, LResource.Skip, Color.Yellow);
            if (FunctionSettingNow.WriteChannel)
                ChannelText.Text = FunctionSettingNow.ChannelList;
            else
            {
                ChannelText.Text = LResource.Default;
                ChannelText.BackColor = Color.Yellow;
            }
            if (FunctionSettingNow.WriteOSD)
                OSDText.Text = FunctionSettingNow.OSDList;
            else
            {
                OSDText.Text = LResource.Default;
                OSDText.BackColor = Color.Yellow;
            }
            if (FunctionSettingNow.WriteSHOP)
                SHOPText.Text = FunctionSettingNow.SHOPList;
            else
            {
                SHOPText.Text = LResource.Default;
                SHOPText.BackColor = Color.Yellow;
            }
            #endregion

            if (midListNow.host != "LocalPC")
            {
                if ((!FunctionSettingNow.WriteWB) && (!cfg_writedone.AutoWhiteBalance))
                {
                    WBPathText.Text = LResource.SkipAutoWB;
                    WBPathText.BackColor = Color.Yellow;
                }
                else
                {
                    // 如果是抄写EDID,则不获取白平衡数据;
                    if (CommonMethod.IsEDIDCopy(midListNow))
                        midListNow.whiteType = "-1";
                    Log.WriteInfoLog("whiteType=" + midListNow.whiteType);
                    switch (midListNow.whiteType)//订单白平衡预置状态
                    {
                        case "0"://旧订单，默认值
                            {
                                if (CommonMethod.GetWhiteBalanceInfo(TestMode.getWhiteBalanceInfoUrl, orderNow, TestMode.MAC, errorDBNow, out WhiteBalanceListNow))
                                {
                                    if (WhiteBalanceListNow.whiteBalanceInfo != null)
                                    {
                                        if (WhiteBalanceListNow.whiteBalanceInfo.isExemption == "0")
                                        {
                                            if (FunctionSettingNow.WriteWB)
                                            {
                                                MessageBoxButtons messButton = MessageBoxButtons.YesNo;
                                                DialogResult dr = MessageBox.Show(LResource.HaveWBfromServer, LResource.Error, messButton);
                                                if (dr == DialogResult.Yes)
                                                {
                                                    FunctionSettingNow.NormalRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmirgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmiggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmibgain) + 256) };
                                                    FunctionSettingNow.CoolRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lbgain) + 256) };
                                                    FunctionSettingNow.WarmRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nbgain) + 256) };
                                                    WBPathText.Text = LResource.LoadFromServer;

                                                }
                                                else
                                                {
                                                    WBPathText.Text = Path.GetFileName(FunctionSettingNow.WBPath);
                                                }
                                            }
                                            else
                                            {
                                                MessageBox.Show(LResource.FindWBfromServer, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                                FunctionSettingNow.WriteWB = true;
                                                FunctionSettingNow.NormalRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmirgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmiggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmibgain) + 256) };
                                                FunctionSettingNow.CoolRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lbgain) + 256) };
                                                FunctionSettingNow.WarmRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nbgain) + 256) };
                                                WBPathText.Text = LResource.LoadFromServer;
                                            }
                                        }
                                        else if (WhiteBalanceListNow.whiteBalanceInfo.isExemption == "1")
                                        {
                                            WBPathText.Text = LResource.WBExemptOrder;
                                            WBPathText.BackColor = Color.Yellow;
                                        }

                                    }
                                    else
                                    {
                                        if (FunctionSettingNow.WriteWB)
                                        {
                                            MessageBoxButtons messButton = MessageBoxButtons.YesNo;
                                            DialogResult dr = MessageBox.Show(LResource.HaveNoWBfromServer, LResource.Error, messButton);
                                            if (dr == DialogResult.OK)
                                            {
                                                WBPathText.Text = Path.GetFileName(FunctionSettingNow.WBPath);
                                            }

                                        }
                                        else
                                        {
                                            WBPathText.Text = LResource.WBNull;
                                            WBPathText.BackColor = Color.Yellow;
                                            FunctionSettingNow.WriteWB = false;
                                        }
                                    }
                                }
                                else
                                {
                                    MessageBox.Show(LResource.GetWBInfoFail);
                                    if (FunctionSettingNow.WriteWB)
                                    {
                                        WBPathText.Text = Path.GetFileName(FunctionSettingNow.WBPath);
                                    }
                                    else
                                    {
                                        WBPathText.Text = LResource.WBNull;
                                        WBPathText.BackColor = Color.Yellow;
                                    }
                                }
                                break;
                            }
                        case "1"://未预置或预置LR数据
                            {
                                if (CommonMethod.GetWhiteBalanceInfo(TestMode.getWhiteBalanceInfoUrl, orderNow, TestMode.MAC, errorDBNow, out WhiteBalanceListNow))
                                {
                                    if (WhiteBalanceListNow.whiteBalanceInfo != null)
                                    {
                                        if (WhiteBalanceListNow.whiteBalanceInfo.isExemption == "0")//0是正常白平衡绑定订单，1是白平衡豁免订单
                                        {
                                            if (FunctionSettingNow.WriteWB)
                                            {
                                                MessageBoxButtons messButton = MessageBoxButtons.YesNo;
                                                DialogResult dr = MessageBox.Show(LResource.HaveWBfromServer, LResource.Error, messButton);
                                                if (dr == DialogResult.Yes)
                                                {
                                                    FunctionSettingNow.NormalRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmirgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmiggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmibgain) + 256) };
                                                    FunctionSettingNow.CoolRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lbgain) + 256) };
                                                    FunctionSettingNow.WarmRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nbgain) + 256) };
                                                    WBPathText.Text = LResource.LoadFromServer;

                                                }
                                                else
                                                {
                                                    WBPathText.Text = Path.GetFileName(FunctionSettingNow.WBPath);
                                                }
                                            }
                                            else
                                            {
                                                MessageBox.Show(LResource.FindWBfromServer, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                                FunctionSettingNow.WriteWB = true;
                                                FunctionSettingNow.NormalRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmirgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmiggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmibgain) + 256) };
                                                FunctionSettingNow.CoolRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lbgain) + 256) };
                                                FunctionSettingNow.WarmRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nbgain) + 256) };
                                                WBPathText.Text = LResource.LoadFromServer;
                                            }
                                        }
                                        else if (WhiteBalanceListNow.whiteBalanceInfo.isExemption == "1")
                                        {
                                            WBPathText.Text = LResource.WBExemptOrder;
                                            WBPathText.BackColor = Color.Yellow;
                                        }

                                    }
                                    else
                                    {
                                        if (FunctionSettingNow.WriteWB)
                                        {
                                            MessageBoxButtons messButton = MessageBoxButtons.YesNo;
                                            DialogResult dr = MessageBox.Show(LResource.HaveNoWBfromServer, LResource.Error, messButton);
                                            if (dr == DialogResult.OK)
                                            {
                                                WBPathText.Text = Path.GetFileName(FunctionSettingNow.WBPath);
                                            }

                                        }
                                        else
                                        {
                                            WBPathText.Text = LResource.WBNull;
                                            WBPathText.BackColor = Color.Yellow;
                                            FunctionSettingNow.WriteWB = false;
                                        }
                                    }
                                }
                                else
                                {
                                    if (FunctionSettingNow.WriteWB)
                                    {
                                        MessageBox.Show(LResource.GetWBInfoFail);
                                        WBPathText.Text = Path.GetFileName(FunctionSettingNow.WBPath);
                                    }
                                    else
                                    {
                                        MessageBox.Show(LResource.GetWBInfoFail2);
                                        this.Close();
                                        return;
                                    }
                                }
                                break;
                            }
                        case "2"://已预置PR数据
                            {
                                if (CommonMethod.GetWhiteBalanceInfo(TestMode.getWhiteBalanceInfoUrl, orderNow, TestMode.MAC, errorDBNow, out WhiteBalanceListNow))
                                {
                                    if (WhiteBalanceListNow.whiteBalanceInfo != null)
                                    {
                                        if (WhiteBalanceListNow.whiteBalanceInfo.isExemption == "0")
                                        {
                                            if (FunctionSettingNow.WriteWB)
                                            {
                                                MessageBoxButtons messButton = MessageBoxButtons.YesNo;
                                                DialogResult dr = MessageBox.Show(LResource.HaveWBfromServer, LResource.Error, messButton);
                                                if (dr == DialogResult.Yes)
                                                {
                                                    FunctionSettingNow.NormalRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmirgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmiggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmibgain) + 256) };
                                                    FunctionSettingNow.CoolRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lbgain) + 256) };
                                                    FunctionSettingNow.WarmRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nbgain) + 256) };
                                                    WBPathText.Text = LResource.LoadFromServer;

                                                }
                                                else
                                                {
                                                    WBPathText.Text = Path.GetFileName(FunctionSettingNow.WBPath);
                                                }
                                            }
                                            else
                                            {
                                                MessageBox.Show(LResource.FindWBfromServer, "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                                FunctionSettingNow.WriteWB = true;
                                                FunctionSettingNow.NormalRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmirgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmiggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.hdmibgain) + 256) };
                                                FunctionSettingNow.CoolRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.lbgain) + 256) };
                                                FunctionSettingNow.WarmRGB = new byte[3] { (byte)Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nrgain), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nggain) + 256), (byte)(Convert.ToDouble(WhiteBalanceListNow.whiteBalanceInfo.nbgain) + 256) };
                                                WBPathText.Text = LResource.LoadFromServer;
                                            }
                                        }
                                        else if (WhiteBalanceListNow.whiteBalanceInfo.isExemption == "1")
                                        {
                                            WBPathText.Text = LResource.WBExemptOrder;
                                            WBPathText.BackColor = Color.Yellow;
                                        }

                                    }
                                    else
                                    {
                                        if (FunctionSettingNow.WriteWB)
                                        {
                                            MessageBoxButtons messButton = MessageBoxButtons.YesNo;
                                            DialogResult dr = MessageBox.Show(LResource.HaveNoWBfromServer, LResource.Error, messButton);
                                            if (dr == DialogResult.OK)
                                            {
                                                WBPathText.Text = Path.GetFileName(FunctionSettingNow.WBPath);
                                            }

                                        }
                                        else
                                        {
                                            WBPathText.Text = LResource.WBNull;
                                            WBPathText.BackColor = Color.Yellow;
                                            FunctionSettingNow.WriteWB = false;
                                        }
                                    }
                                }
                                else
                                {
                                    MessageBox.Show(LResource.GetWBInfoFail);
                                    if (FunctionSettingNow.WriteWB)
                                    {
                                        WBPathText.Text = Path.GetFileName(FunctionSettingNow.WBPath);
                                    }
                                    else
                                    {
                                        WBPathText.Text = LResource.WBNull;
                                        WBPathText.BackColor = Color.Yellow;
                                    }
                                }
                                break;
                            }
                        case "3"://已预置客户指定数据
                            {
                                if (FunctionSettingNow.WriteWB)
                                {
                                    MessageBox.Show(LResource.PreloadCustomerWB);
                                    this.Close();
                                    return;
                                }
                                break;
                            }
                    }
                }
            }
            else
            {
                if (FunctionSettingNow.WriteWB)
                {
                    WBPathText.Text = Path.GetFileName(FunctionSettingNow.WBPath);
                }
                else
                {
                    WBPathText.Text = LResource.WBNull;
                    WBPathText.BackColor = Color.Yellow;
                }
            }
            try
            {
                TVPort.PortName = FunctionSettingNow.TVCOM;
                TVPort.BaudRate = Convert.ToInt32(FunctionSettingNow.TVBaud);
                TVPort.WriteBufferSize = 20480;
                TVPort.ReadBufferSize = 20480;
                TVPort.Parity = (Parity)FunctionSettingNow.TVParity;
                TVPort.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.Close();
            }
            this.Text = FunctionSettingNow.TVCOM;
        }

        private void OperationPanel_Load(object sender, EventArgs e)
        {
            if (midListNow.host == "LocalPC")
            {
                OrderText.Text = orderNow;
                ClientTypeText.Text = midListNow.clienttype;
                SVText.Text = midListNow.version;
                ProjectIDText.Text = midListNow.projectid;
                GetLocalKeysCount();
            }
            else if (!preloadNow)
            {
                OrderText.Text = orderNow;
                ClientTypeText.Text = midListNow.clienttype;
                SVText.Text = midListNow.version;
                ProjectIDText.Text = midListNow.projectid;
                UpdateKeys(midListNow.keytype, false);
            }
            else
            {
                OrderText.Text = MidAddressNow.order;
                ClientTypeText.Text = MidAddressNow.ctype;
                SVText.Text = MidAddressNow.version;
                ProjectIDText.Text = MidAddressNow.pid;
            }
            SNText.Text = "";
            SNTextFocus = new Thread(TextBoxFocus);
            SNTextFocus.Start();
            SNText.Focus();
        }

        /// <summary>
        /// 强制聚焦扫描框
        /// </summary>
        public void TextBoxFocus()
        {
            while (true)
            {
                if (FocusMark)
                {
                    if (this.CaptionBackColorTop != Color.Yellow || this.CaptionBackColorBottom != Color.Orange)
                    {
                        if (this.InvokeRequired)
                        {
                            this.BeginInvoke(new Action(() =>
                            {
                                this.CaptionBackColorTop = Color.Yellow;
                                this.CaptionBackColorBottom = Color.Orange;
                                this.Refresh();
                            }));
                        }
                    }
                    if (SNText.InvokeRequired)
                    {
                        SNText.BeginInvoke(new Action(() =>
                        {
                            if (!SNText.Focus())
                            {
                                SNText.Focus();
                            }
                        }));
                    }
                }
                Thread.Sleep(500);
            }
        }

        private void OperationPanel_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (TVPort.IsOpen)
                TVPort.Close();
            DeleteIntptr(this.Handle);
            GC.Collect();
        }

        /// <summary>
        /// 扫描触发抄写，以回车终结触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SNText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                keyInfo = new KeyInfo();
                FocusMark = false;
                SNKeyDownEven(this.Handle);
                SetInitialStatus();
                SN = SNText.Text;
                SNText.Enabled = false;
                if (FunctionSettingNow.BarcodeLimit)
                {
                    if (SN.Length != FunctionSettingNow.BarcodeLength || !SN.StartsWith(FunctionSettingNow.BarcodeKeyword))
                    {
                        MessageBox.Show(string.Format("{0}\r\nSN=<{1}, Len={2}>\r\nKeyword=<{3}>", LResource.WrongBarcode, SN, SN.Length, FunctionSettingNow.BarcodeKeyword));
                        SNText.Enabled = true;
                        SNText.Text = "";
                        return;
                    }

                    if (!FunctionSettingNow.BarcodeWrite && (midListNow.keytype != null && midListNow.keytype.ContainsKey("DSN")))
                    {
                        // 如果不是全大写字母+数字,返回;
                        Regex r = new Regex(@"^[A-Z0-9]+$");
                        if (!r.Match(SN).Success)
                        {
                            MessageBox.Show(string.Format("{0}\r\nSN=<{1}, Len={2}>\r\nKeyword=<{3}>", LResource.WrongBarcode, SN, SN.Length, FunctionSettingNow.BarcodeKeyword));
                            SNText.Enabled = true;
                            SNText.Text = "";
                            return;
                        }
                    }
                }

                #region 只有惠州工厂才启用G客户防呆措施;
                if (FunctionSettingNow.NTF)
                {
                    StringBuilder strValue = new StringBuilder(256);
                    // 获取上一次的SN号;
                    CommonMethod.GetProfileString("MOKAFactoryTools", "LastGSN", "", strValue, 256);
                    if (strValue.ToString().Equals(SN, StringComparison.OrdinalIgnoreCase))
                    {
                        // 连续测试中累计失败的次数;
                        int lastCount = 0;
                        CommonMethod.GetProfileString("MOKAFactoryTools", "GFailCount", "0", strValue, 256);
                        int.TryParse(strValue.ToString(), out lastCount);
                        // NTF规则：连续测试中累计出现2次Fail,禁止测试.
                        if (lastCount >= FunctionSettingNow.GFoolProofingCount)
                        {
                            Verify dlg = new Verify("累计出现2次Fail，禁止测试！" + "\r\n" + SN);
                            dlg.ShowDialog();
                            SNText.Enabled = true;
                            SNText.Text = "";
                            return;
                        }
                    }

                    // 根据SN获取订单类型;
                    string strOrderType;
                    string strErrorMsg;
                    if (!GMethod.GetOrderTypeFromSN(SN, out strOrderType, out strErrorMsg))
                    {
                        Verify dlg = new Verify("根据SN获取订单类型失败，停止测试！" + "\r\nSN:" + SN);
                        dlg.ShowDialog();
                        Log.WriteErrorLog(string.Format("SN={0},错误={1}", SN, strErrorMsg));
                        SNText.Enabled = true;
                        SNText.Text = "";
                        return;
                    }

                    if (strOrderType.Equals("量产"))
                        nOrderType = 1;
                    else if (strOrderType.Equals("试产"))
                        nOrderType = 0;
                    else
                    {
                        Verify dlg = new Verify("根据SN获取订单类型异常，停止测试！" + "\r\n" + SN);
                        dlg.ShowDialog();
                        Log.WriteErrorLog(String.Format("{0}获取订单类型异常={1}", SN, strOrderType));
                        SNText.Enabled = true;
                        SNText.Text = "";
                        return;
                    }
                } 
                else if ( FunctionSettingNow.SNDoubleTips )
                {
                    StringBuilder strValue = new StringBuilder(256);
                    // 获取上一次的SN号;
                    CommonMethod.GetProfileString("MOKAFactoryTools", "LastSN", "", strValue, 256);
                    if (strValue.ToString().Equals(SN, StringComparison.OrdinalIgnoreCase))
                    {
                        if ( MessageBox.Show("该SN已连续使用两次，可能误用到其他机器，请确认是否继续", "提示", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
                        {
                            SNText.Enabled = true;
                            SNText.Text = "";
                            return;
                        }
                    }

                    CommonMethod.WriteProfileString("MOKAFactoryTools", "LastSN", SN);
                }
                #endregion

                if (preloadNow)
                {
                    bool copydone = false;
                    string keyjson = SQLiteHelper.Getkeys(localDBNow, SNText.Text.Trim(), out copydone);
                    if (FunctionSettingNow.NoDoublewrite && copydone)
                    {
                        MessageBox.Show(LResource.FindcopiedSN + SN);
                        SNText.Enabled = true;
                        SNText.Focus();
                    }
                    else if (keyjson.Length > 0)
                    {
                        #region 解决Json对象空导致的Bug.
                        Func<JToken, string> GetJsonValue = (JsonObj) =>
                        {
                            if (JsonObj == null )
                                return "";

                            return JsonObj.Value<string>();
                        };
                        #endregion
                        JObject jObject = JObject.Parse(keyjson);
                        keyInfo.DID.data = GetJsonValue(jObject["did"]);
                        keyInfo.Mac.data = GetJsonValue(jObject["mac"]);
                        keyInfo.HDCP.data = GetJsonValue(jObject["hdcp"]);
                        keyInfo.HDCP22.data = GetJsonValue(jObject["hdcp22"]);
                        //keyInfo.WiDi.data = GetJsonValue(jObject["widi"]);
                        keyInfo.Widevine.data = GetJsonValue(jObject["widevine"]);
                        keyInfo.ESN.data = GetJsonValue(jObject["esn"]);
                        keyInfo.CI_plus.data = GetJsonValue(jObject["cikey"]);
                        keyInfo.MGK.data = GetJsonValue(jObject["mgk"]);
                        keyInfo.Attestation.data = GetJsonValue(jObject["attestation"]);
                        keyInfo.Fairplay.data = GetJsonValue(jObject["fairplay"]);
                        keyInfo.ECP.data = GetJsonValue(jObject["ecp"]);
                        keyInfo.WiFi_MAC.data = GetJsonValue(jObject["wifimac"]);
                        keyInfo.BT_MAC.data = GetJsonValue(jObject["btmac"]);
                        keyInfo.LEK.data = GetJsonValue(jObject["lek"]);
                        keyInfo.PEK.data = GetJsonValue(jObject["pek"]);
                        keyInfo.Playready.data = GetJsonValue(jObject["playready"]);
                        keyInfo.Hashkey.data = GetJsonValue(jObject["hash"]);
                        keyInfo.YouTube_KEY.data = GetJsonValue(jObject["youtubekey"]);
                        keyInfo.ACASKey_Data.data = GetJsonValue(jObject["acaskey_data"]);
                        //keyInfo.ACASKey_Tool.data = GetJsonValue(jObject["acaskey_tool"]);
                        keyInfo.DAK.data = GetJsonValue(jObject["dak"]);
                        keyInfo.FVP.data = GetJsonValue(jObject["FVP"]);

                        WriteDID.Checked = (keyInfo.DID.Length > 0 && m_writedid.Text != LResource.Skip);
                        if (WriteDID.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB DeviceID=" + keyInfo.DID.data);
                        WriteMac.Checked = (keyInfo.Mac.Length > 0 && m_writemac.Text != LResource.Skip);
                        if (WriteMac.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB Mac=" + keyInfo.Mac.data);
                        WriteHDCP.Checked = (keyInfo.HDCP.Length > 0 && m_writehdcp.Text != LResource.Skip);
                        if (WriteHDCP.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB HDCP=" + keyInfo.HDCP.data);
                        WriteHDCP22.Checked = (keyInfo.HDCP22.Length > 0 && m_writehdcp22.Text != LResource.Skip);
                        if (WriteHDCP22.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB HDCP22=" + keyInfo.HDCP22.data);
                        WriteWidevine.Checked = (keyInfo.Widevine.Length > 0 && m_writewidevine.Text != LResource.Skip);
                        if (WriteWidevine.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB Widevine=" + keyInfo.Widevine.data);
                        WriteESN.Checked = (keyInfo.ESN.Length > 0 && m_writeesn.Text != LResource.Skip);
                        if (WriteESN.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB ESN=" + keyInfo.ESN.data);
                        WriteCiplus.Checked = (keyInfo.CI_plus.Length > 0 && m_writeci.Text != LResource.Skip);
                        if (WriteCiplus.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB Ci=" + keyInfo.CI_plus.data);
                        WriteMGK.Checked = (keyInfo.MGK.Length > 0 && m_writeMGK.Text != LResource.Skip);
                        if (WriteMGK.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB MGK=" + keyInfo.MGK.data);
                        WriteAttestation.Checked = (keyInfo.Attestation.Length > 0 && m_writeattestation.Text != LResource.Skip);
                        if (WriteAttestation.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB Attestation=" + keyInfo.Attestation.data);
                        WriteFairplay.Checked = (keyInfo.Fairplay.Length > 0 && m_writeFairplay.Text != LResource.Skip);
                        if (WriteFairplay.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB Fairplay=" + keyInfo.Fairplay.data);
                        WriteECP.Checked = (keyInfo.ECP.Length > 0 && m_writeECP.Text != LResource.Skip);
                        if (WriteECP.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB ECP=" + keyInfo.ECP.data);
                        WriteWifiMac.Checked = (keyInfo.WiFi_MAC.Length > 0 && m_writeWifiMac.Text != LResource.Skip);
                        if (WriteWifiMac.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB WifiMac=" + keyInfo.WiFi_MAC.data);
                        WriteBTMac.Checked = (keyInfo.BT_MAC.Length > 0 && m_writeBTMac.Text != LResource.Skip);
                        if (WriteBTMac.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB BTMac=" + keyInfo.BT_MAC.data);
                        WriteLEK.Checked = (keyInfo.LEK.Length > 0 && m_writeLEK.Text != LResource.Skip);
                        if (WriteLEK.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB LEK=" + keyInfo.LEK.data);
                        WritePEK.Checked = (keyInfo.PEK.Length > 0 && m_writePEK.Text != LResource.Skip);
                        if (WritePEK.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB PEK=" + keyInfo.PEK.data);
                        WritePlayready.Checked = (keyInfo.Playready.Length > 0 && m_writePlayready.Text != LResource.Skip);
                        if (WritePlayready.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB Playready=" + keyInfo.Playready.data);
                        WriteHash.Checked = (keyInfo.Hashkey.Length > 0 && m_writeHash.Text != LResource.Skip);
                        if (WriteHash.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB Hashkey=" + keyInfo.Hashkey.data);
                        WriteYouTube.Checked = (keyInfo.YouTube_KEY.Length > 0 && m_writeYouTube.Text != LResource.Skip);
                        if (WriteYouTube.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB YouTube_KEY=" + keyInfo.YouTube_KEY.data);
                        WriteACASKey.Checked = (keyInfo.ACASKey_Data.Length > 0 && m_writeACASKey.Text != LResource.Skip);
                        if (WriteACASKey.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB ACAS_KEY=" + keyInfo.ACASKey_Data.data);
                        WriteDAK.Checked = (keyInfo.DAK.Length > 0 && m_writeDAK.Text != LResource.Skip);
                        if (WriteDAK.Checked)
                            Log.WriteGetKeyLog("\r\nLocal DB DAK=" + keyInfo.DAK.data);
                        WriteFVP.Checked = m_writeFVP.Text != LResource.Skip;
                        WriteDSN.Checked = (keyInfo.DSN.Length > 0 && m_writeDSN.Text != LResource.Skip);
                        //WriteDolby.Checked = (keyInfo.Dolby.Length > 0 && m_writeDolby.Text != LResource.Skip);
                        WritePSN.Checked = FunctionSettingNow.BarcodeWrite;

                        timer1.Start();
                        Thread t = new Thread(Writekey);
                        t.Start();
                    }
                    else
                    {
                        MessageBox.Show(LResource.FindNullSnInDB + SN);
                        SNText.Enabled = true;
                        SNText.Focus();
                    }
                }
                else
                {
                    Onlinemode();
                }

                // 抄写成功后才清空;
                //SNText.Text = "";
            }
        }

        /// <summary>
        /// 设置成功状态显示
        /// </summary>
        /// <param name="label"></param>
        public void SetsuccessStatus(Label label)
        {
            if (label.InvokeRequired && label.Text != LResource.Skip)
            {
                //BeginInvoke(new Action<string>(x => { label.Text = x.ToString(); }), 参数);
                label.BeginInvoke(new Action(() => { label.Text = "OK"; label.BackColor = Color.FromArgb(128, 255, 128); }));
            }

        }

        /// <summary>
        /// 设置失败状态显示
        /// </summary>
        /// <param name="label"></param>
        public void SetfailStatus(Label label)
        {
            if (label.InvokeRequired)
            {
                label.BeginInvoke(new Action(() => { label.Text = "NG"; label.BackColor = Color.Red; }));
            }
        }

        /// <summary>
        /// 设置扫描框为输入状态
        /// </summary>
        /// <param name="textBox"></param>
        public void EnableText(TextBox textBox)
        {
            if (textBox.InvokeRequired)
            {
                textBox.BeginInvoke(new Action(() => { textBox.Enabled = true; textBox.Text = ""; textBox.Focus(); }));
            }
            else
            {
                textBox.Enabled = true;
                textBox.Focus();
                textBox.Text = "";
            }
        }

        /// <summary>
        /// 设置按钮为可点击状态
        /// </summary>
        /// <param name="button"></param>
        public void EnableButton(Button button)
        {
            if (button.InvokeRequired)
            {
                button.BeginInvoke(new Action(() => { button.Enabled = true; }));
            }
            else
                button.Enabled = true;
        }

        /// <summary>
        /// 设置特殊的文本和颜色
        /// </summary>
        /// <param name="label">标签控件</param>
        /// <param name="str">需要显示的文本</param>
        /// <param name="color">需要设置的控件背景颜色</param>
        public void SetspecificText(Label label, string str, Color color)
        {
            if (label.InvokeRequired)
            {
                BeginInvoke(new Action<string>(x => { label.Text = x.ToString(); }), str);
                label.BeginInvoke(new Action(() => { label.BackColor = color; }));
            }
            else
            {
                label.Text = str;
                label.BackColor = color;
            }
        }

        /// <summary>
        /// 设置标签控件颜色
        /// </summary>
        /// <param name="label">标签控件对象</param>
        /// <param name="color">需要设置的标签背景颜色</param>
        public void SetcolorStatus(Label label, Color color)
        {
            if (label.InvokeRequired)
            {
                label.BeginInvoke(new Action(() => { label.BackColor = color; }));
            }
        }

        /// <summary>
        /// 跨线程关闭窗口
        /// </summary>
        /// <param name="label"></param>
        /// <param name="color"></param>
        public void Closeform()
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action(() => { this.Close(); }));
            }
        }

        /// <summary>
        /// 设置标签控件文本
        /// </summary>
        /// <param name="label">标签控件对象</param>
        /// <param name="color">需要设置的标签文本</param>
        public void SetTextStatus(Label label, string txt)
        {
            if (label.InvokeRequired)
            {
                label.BeginInvoke(new Action(() => { label.Text = txt; }));
            }
            else
                label.Text = txt;
        }

        /// <summary>
        /// 线程内&跨线程设置key数量显示控件
        /// </summary>
        /// <param name="label">数量提示控件</param>
        /// <param name="str">数量值</param>
        /// <param name="status">状态，0为正常，1为获取失败，2为数量不足</param>
        public void SetKeyCountStatus(Label label, string str, int status)
        {
            if (label.InvokeRequired)
            {
                BeginInvoke(new Action<string>(x => { label.Text = x.ToString(); }), str);
                switch (status)
                {
                    case 0:
                        label.BeginInvoke(new Action(() => { label.ForeColor = Color.Green; }));
                        break;
                    case 1:
                        label.BeginInvoke(new Action(() => { label.BackColor = Color.Red; }));
                        break;
                    case 2:
                        label.BeginInvoke(new Action(() => { label.ForeColor = Color.Red; }));
                        break;
                }
            }
            else
            {
                label.Text = str;
                switch (status)
                {
                    case 0:
                        label.ForeColor = Color.Green; ;
                        break;
                    case 1:
                        label.BackColor = Color.Red;
                        break;
                    case 2:
                        label.ForeColor = Color.Red;
                        break;
                }
            }
        }

        /// <summary>
        /// 线程内&跨线程设置checkbox控件的checked值
        /// </summary>
        /// <param name="checkBox">checkbox控件</param>
        /// <param name="status">需要设置的布尔状态</param>
        public void SetCheckboxStatus(CheckBox checkBox, bool status)
        {
            if (checkBox.InvokeRequired)
            {
                BeginInvoke(new Action<bool>(x => { checkBox.Checked = x; }), status);
            }
            else
            {
                checkBox.Checked = status;
            }
        }

        /// <summary>
        /// 重置控件状态，skip除外
        /// </summary>
        public void SetInitialStatus()
        {
            this.CaptionBackColorTop = Color.RoyalBlue;
            this.CaptionBackColorBottom = Color.Cyan;
            this.Refresh();
            /////////////////////////////////////////////////////////////
            #region  Set Write;
            if (m_writeci.Text != LResource.Skip)
            {
                m_writeci.Text = "Null";
                m_writeci.BackColor = Color.Transparent;
            }
            if (m_writemac.Text != LResource.Skip)
            {
                m_writemac.Text = "Null";
                m_writemac.BackColor = Color.Transparent;
            }
            if (m_writedid.Text != LResource.Skip)
            {
                m_writedid.Text = "Null";
                m_writedid.BackColor = Color.Transparent;
            }
            if (m_writeesn.Text != LResource.Skip)
            {
                m_writeesn.Text = "Null";
                m_writeesn.BackColor = Color.Transparent;
            }
            if (m_writewidevine.Text != LResource.Skip)
            {
                m_writewidevine.Text = "Null";
                m_writewidevine.BackColor = Color.Transparent;
            }
            if (m_writehdcp.Text != LResource.Skip)
            {
                m_writehdcp.Text = "Null";
                m_writehdcp.BackColor = Color.Transparent;
            }
            if (m_writehdcp22.Text != LResource.Skip)
            {
                m_writehdcp22.Text = "Null";
                m_writehdcp22.BackColor = Color.Transparent;
            }
            if (m_writeattestation.Text != LResource.Skip)
            {
                m_writeattestation.Text = "Null";
                m_writeattestation.BackColor = Color.Transparent;
            }
            if (m_writeMGK.Text != LResource.Skip)
            {
                m_writeMGK.Text = "Null";
                m_writeMGK.BackColor = Color.Transparent;
            }
            if (m_writeFairplay.Text != LResource.Skip)
            {
                m_writeFairplay.Text = "Null";
                m_writeFairplay.BackColor = Color.Transparent;
            }
            if (m_writeECP.Text != LResource.Skip)
            {
                m_writeECP.Text = "Null";
                m_writeECP.BackColor = Color.Transparent;
            }
            if (m_writeLEK.Text != LResource.Skip)
            {
                m_writeLEK.Text = "Null";
                m_writeLEK.BackColor = Color.Transparent;
            }
            if (m_writePEK.Text != LResource.Skip)
            {
                m_writePEK.Text = "Null";
                m_writePEK.BackColor = Color.Transparent;
            }
            if (m_writeHash.Text != LResource.Skip)
            {
                m_writeHash.Text = "Null";
                m_writeHash.BackColor = Color.Transparent;
            }
            if (m_writeDSN.Text != LResource.Skip)
            {
                m_writeDSN.Text = "Null";
                m_writeDSN.BackColor = Color.Transparent;
            }
            if (m_writeWifiMac.Text != LResource.Skip)
            {
                m_writeWifiMac.Text = "Null";
                m_writeWifiMac.BackColor = Color.Transparent;
            }
            if (m_writeBTMac.Text != LResource.Skip)
            {
                m_writeBTMac.Text = "Null";
                m_writeBTMac.BackColor = Color.Transparent;
            }
            if (m_writeDSN.Text != LResource.Skip)
            {
                m_writeDSN.Text = "Null";
                m_writeDSN.BackColor = Color.Transparent;
            }
            if (m_writePlayready.Text != LResource.Skip)
            {
                m_writePlayready.Text = "Null";
                m_writePlayready.BackColor = Color.Transparent;
            }
            if (m_writeYouTube.Text != LResource.Skip)
            {
                m_writeYouTube.Text = "Null";
                m_writeYouTube.BackColor = Color.Transparent;
            }
            if (m_writePSN.Text != LResource.Skip)
            {
                m_writePSN.Text = "Null";
                m_writePSN.BackColor = Color.Transparent;
            }
            if (m_writeACASKey.Text != LResource.Skip)
            {
                m_writeACASKey.Text = "Null";
                m_writeACASKey.BackColor = Color.Transparent;
            }
            if (m_writeEDIDPID.Text != LResource.Skip)
            {
                m_writeEDIDPID.Text = "Null";
                m_writeEDIDPID.BackColor = Color.Transparent;
            }
            if (m_writeEDIDName.Text != LResource.Skip)
            {
                m_writeEDIDName.Text = "Null";
                m_writeEDIDName.BackColor = Color.Transparent;
            }
            #endregion
            /////////////////////////////////////////////////////////////
            #region Write Check;
            if (m_checkci.Text != LResource.Skip)
            {
                m_checkci.Text = "Null";
                m_checkci.BackColor = Color.Transparent;
            }
            if (m_checkmac.Text != LResource.Skip)
            {
                m_checkmac.Text = "Null";
                m_checkmac.BackColor = Color.Transparent;
            }
            if (m_checkdid.Text != LResource.Skip)
            {
                m_checkdid.Text = "Null";
                m_checkdid.BackColor = Color.Transparent;
            }
            if (m_checkesn.Text != LResource.Skip)
            {
                m_checkesn.Text = "Null";
                m_checkesn.BackColor = Color.Transparent;
            }
            if (m_checkwidevine.Text != LResource.Skip)
            {
                m_checkwidevine.Text = "Null";
                m_checkwidevine.BackColor = Color.Transparent;
            }
            if (m_checkhdcp.Text != LResource.Skip)
            {
                m_checkhdcp.Text = "Null";
                m_checkhdcp.BackColor = Color.Transparent;
            }
            if (m_checkhdcp22.Text != LResource.Skip)
            {
                m_checkhdcp22.Text = "Null";
                m_checkhdcp22.BackColor = Color.Transparent;
            }
            if (m_checkattestation.Text != LResource.Skip)
            {
                m_checkattestation.Text = "Null";
                m_checkattestation.BackColor = Color.Transparent;
            }
            if (m_checkMGK.Text != LResource.Skip)
            {
                m_checkMGK.Text = "Null";
                m_checkMGK.BackColor = Color.Transparent;
            }
            if (m_checkFairplay.Text != LResource.Skip)
            {
                m_checkFairplay.Text = "Null";
                m_checkFairplay.BackColor = Color.Transparent;
            }
            if (m_checkECP.Text != LResource.Skip)
            {
                m_checkECP.Text = "Null";
                m_checkECP.BackColor = Color.Transparent;
            }
            if (m_checkLEK.Text != LResource.Skip)
            {
                m_checkLEK.Text = "Null";
                m_checkLEK.BackColor = Color.Transparent;
            }
            if (m_checkPEK.Text != LResource.Skip)
            {
                m_checkPEK.Text = "Null";
                m_checkPEK.BackColor = Color.Transparent;
            }
            if (m_checkHash.Text != LResource.Skip)
            {
                m_checkHash.Text = "Null";
                m_checkHash.BackColor = Color.Transparent;
            }
            if (m_checkDSN.Text != LResource.Skip)
            {
                m_checkDSN.Text = "Null";
                m_checkDSN.BackColor = Color.Transparent;
            }
            if (m_checkWifiMac.Text != LResource.Skip)
            {
                m_checkWifiMac.Text = "Null";
                m_checkWifiMac.BackColor = Color.Transparent;
            }
            if (m_checkBTMac.Text != LResource.Skip)
            {
                m_checkBTMac.Text = "Null";
                m_checkBTMac.BackColor = Color.Transparent;
            }
            if (m_checkDSN.Text != LResource.Skip)
            {
                m_checkDSN.Text = "Null";
                m_checkDSN.BackColor = Color.Transparent;
            }
            if (m_checkPlayready.Text != LResource.Skip)
            {
                m_checkPlayready.Text = "Null";
                m_checkPlayready.BackColor = Color.Transparent;
            }
            if (m_checkYouTube.Text != LResource.Skip)
            {
                m_checkYouTube.Text = "Null";
                m_checkYouTube.BackColor = Color.Transparent;
            }
            if (m_checkACASKey.Text != LResource.Skip)
            {
                m_checkACASKey.Text = "Null";
                m_checkACASKey.BackColor = Color.Transparent;
            }
            #endregion
            /////////////////////////////////////////////////////////////
            #region  Read Check;
            if (m_readci.Text != LResource.Skip)
            {
                m_readci.Text = "Null";
                m_readci.BackColor = Color.Transparent;
            }
            if (m_readmac.Text != LResource.Skip)
            {
                m_readmac.Text = "Null";
                m_readmac.BackColor = Color.Transparent;
            }
            if (m_readdid.Text != LResource.Skip)
            {
                m_readdid.Text = "Null";
                m_readdid.BackColor = Color.Transparent;
            }
            if (m_readesn.Text != LResource.Skip)
            {
                m_readesn.Text = "Null";
                m_readesn.BackColor = Color.Transparent;
            }
            if (m_readwidevine.Text != LResource.Skip)
            {
                m_readwidevine.Text = "Null";
                m_readwidevine.BackColor = Color.Transparent;
            }
            if (m_readhdcp.Text != LResource.Skip)
            {
                m_readhdcp.Text = "Null";
                m_readhdcp.BackColor = Color.Transparent;
            }
            if (m_readhdcp22.Text != LResource.Skip)
            {
                m_readhdcp22.Text = "Null";
                m_readhdcp22.BackColor = Color.Transparent;
            }
            if (m_readattestation.Text != LResource.Skip)
            {
                m_readattestation.Text = "Null";
                m_readattestation.BackColor = Color.Transparent;
            }
            if (m_readMGK.Text != LResource.Skip)
            {
                m_readMGK.Text = "Null";
                m_readMGK.BackColor = Color.Transparent;
            }
            if (m_readFairplay.Text != LResource.Skip)
            {
                m_readFairplay.Text = "Null";
                m_readFairplay.BackColor = Color.Transparent;
            }
            if (m_readECP.Text != LResource.Skip)
            {
                m_readECP.Text = "Null";
                m_readECP.BackColor = Color.Transparent;
            }
            if (m_readLEK.Text != LResource.Skip)
            {
                m_readLEK.Text = "Null";
                m_readLEK.BackColor = Color.Transparent;
            }
            if (m_readPEK.Text != LResource.Skip)
            {
                m_readPEK.Text = "Null";
                m_readPEK.BackColor = Color.Transparent;
            }
            if (m_readHash.Text != LResource.Skip)
            {
                m_readHash.Text = "Null";
                m_readHash.BackColor = Color.Transparent;
            }
            if (m_readDSN.Text != LResource.Skip)
            {
                m_readDSN.Text = "Null";
                m_readDSN.BackColor = Color.Transparent;
            }
            if (m_readWifiMac.Text != LResource.Skip)
            {
                m_readWifiMac.Text = "Null";
                m_readWifiMac.BackColor = Color.Transparent;
            }
            if (m_readBTMac.Text != LResource.Skip)
            {
                m_readBTMac.Text = "Null";
                m_readBTMac.BackColor = Color.Transparent;
            }
            if (m_readDSN.Text != LResource.Skip)
            {
                m_readDSN.Text = "Null";
                m_readDSN.BackColor = Color.Transparent;
            }
            if (m_readPlayready.Text != LResource.Skip)
            {
                m_readPlayready.Text = "Null";
                m_readPlayready.BackColor = Color.Transparent;
            }
            if (m_readYouTube.Text != LResource.Skip)
            {
                m_readYouTube.Text = "Null";
                m_readYouTube.BackColor = Color.Transparent;
            }
            if (m_readPSN.Text != LResource.Skip)
            {
                m_readPSN.Text = "Null";
                m_readPSN.BackColor = Color.Transparent;
            }
            if (m_readACASID.Text != LResource.Skip)
            {
                m_readACASID.Text = "Null";
                m_readACASID.BackColor = Color.Transparent;
            }
            if (m_readEDIDPID.Text != LResource.Skip)
            {
                m_readEDIDPID.Text = "Null";
                m_readEDIDPID.BackColor = Color.Transparent;
            }
            if (m_readEDIDName.Text != LResource.Skip)
            {
                m_readEDIDName.Text = "Null";
                m_readEDIDName.BackColor = Color.Transparent;
            }
            if (m_readACASKey.Text != LResource.Skip)
            {
                m_readACASKey.Text = "Null";
                m_readACASKey.BackColor = Color.Transparent;
            }
            #endregion

            ResultStatus.Text = "Wait";
            ResultStatus.BackColor = Color.Transparent;

            SHOPText.BackColor = Color.Transparent;
            OSDText.BackColor = Color.Transparent;
            WBPathText.BackColor = Color.Transparent;
            ProductMsg_Text.BackColor = Color.Transparent;
        }

        /// <summary>
        /// 生成报文;
        /// </summary>
        /// <returns></returns>
        public string GenerateReportInfo()
        {
            #region 移除非IDM抄写的Key;
            if (FunctionSettingNow.MITVEnable && _MiKey != null)
            {
                // 配置要抄写的选项;
                if (_MiKey.EthernetMac != null)
                    SetCheckboxStatus(WriteMac, false);

                if (_MiKey.BTMac != null)
                    SetCheckboxStatus(WriteBTMac, false);

                if (_MiKey.DSN != null)
                    SetCheckboxStatus(WriteDSN, false);

                if (_MiKey.WIFIMAC != null)
                    SetCheckboxStatus(WriteWifiMac, false);
            }
            #endregion

            #region 生成IDMKey报文;
            string reportdata = "";
            if (SN.Trim().Length > 0)
                reportdata += "sn=" + SN + "&";

            if (WriteDID.Checked)
                reportdata += "deviceid=" + keyInfo.DID.data + "&";

            if (WriteMac.Checked)
                reportdata += "mac=" + keyInfo.Mac.data + "&";

            if (WriteWifiMac.Checked)
                reportdata += "wifimac=" + keyInfo.WiFi_MAC.data + "&";

            if (WriteBTMac.Checked)
                reportdata += "btmac=" + keyInfo.BT_MAC.data + "&";

            if (WriteHDCP.Checked)
                reportdata += "hdcpkey=" + keyInfo.HDCP.data + "&";

            if (WriteHDCP22.Checked)
                reportdata += "hdcpkey2=" + keyInfo.HDCP22.data + "&";

            if (WriteESN.Checked)
                reportdata += "netfilxesn=" + keyInfo.ESN.data + "&";

            if (WritePEK.Checked)
                reportdata += "pek=" + keyInfo.PEK.data + "&";

            if (WriteYouTube.Checked)
                reportdata += "youtubekey=" + keyInfo.YouTube_KEY.data + "&";

            if (WriteWidevine.Checked)
                reportdata += "widevine=" + keyInfo.Widevine.data + "&";

            if (WriteCiplus.Checked)
                reportdata += "cikey=" + keyInfo.CI_plus.data + "&";

            if (WriteAttestation.Checked)
                reportdata += "attestationmd5=" + keyInfo.AttestationMD5.data + "&";

            if (WriteMGK.Checked)
                reportdata += "mgk=" + keyInfo.MGK.data + "&";

            if (WriteFairplay.Checked)
                reportdata += "fairplay=" + keyInfo.Fairplay.data + "&";

            if (WriteECP.Checked)
                reportdata += "ecp=" + keyInfo.ECP.data + "&";

            if (WriteLEK.Checked)
                reportdata += "lek=" + keyInfo.LEK.data + "&";

            if (WritePlayready.Checked)
                reportdata += "playready=" + keyInfo.Playready.data + "&";

            if (WriteHash.Checked)
                reportdata += "hash=" + keyInfo.Hashkey.data + "&";

            if (WriteEDIDPID.Checked)
                reportdata += "EDIDPid=" + keyInfo.EDIDPid.data + "&";

            if (WriteEDIDName.Checked)
                reportdata += "EDIDModeName=" + keyInfo.EDIDModelName.data + "&";

            if (WriteACASKey.Checked)
                reportdata += "acas_tool=" + keyInfo.ACASKey_Tool.data + "&";

            if (WriteACASKey.Checked)
                reportdata += "acas_data=" + keyInfo.ACASKey_Data.data + "&";

            if (WriteDAK.Checked)
                reportdata += "DAK=" + keyInfo.DAK.data + "&";

            if (ProjectIDNote.Text != LResource.SkipCovering)
                reportdata += "projectid=" + ProjectIDText.Text + "&";

            if (FunctionSettingNow.WriteWB)
                reportdata += "wbNormal=" + FunctionSettingNow.NormalRGB[0].ToString() + ":" + FunctionSettingNow.NormalRGB[1].ToString() + ":" + FunctionSettingNow.NormalRGB[2].ToString() + "&" + "wbCool=" + FunctionSettingNow.CoolRGB[0].ToString() + ":" + FunctionSettingNow.CoolRGB[1].ToString() + ":" + FunctionSettingNow.CoolRGB[2].ToString() + "&" + "wbWarm=" + FunctionSettingNow.WarmRGB[0].ToString() + ":" + FunctionSettingNow.WarmRGB[1].ToString() + ":" + FunctionSettingNow.WarmRGB[2].ToString() + "&";

            reportdata += "toolVersion=" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString() + "&";

            return reportdata;
            #endregion
        }

        public bool ReportMIInfo(out string msg)
        {
            msg = "";
            // 上报MIKey抄写结果;
            ReportMIKey reportMIKey = new ReportMIKey();
            reportMIKey.EthernetMAC = _MiKey.EthernetMac;
            reportMIKey.BTMAC = _MiKey.BTMac;
            reportMIKey.WIFIMAC = _MiKey.WIFIMAC;
            // 读取HDCP长度赋值;
            reportMIKey.HDCP22 = _MiKey._HDCP22.ToString();
            reportMIKey.HDCP14 = _MiKey._HDCP14.ToString();
            // 返回的PSN作为ChipMN和ChipSN;
            reportMIKey.ChipMN = _MiKey._PSN;
            reportMIKey.ChipSN = _MiKey._PSN;
            reportMIKey.DSN = _MiKey.DSN;
            reportMIKey.TVMN = _MiKey.TVMN;
            reportMIKey.TVSN = SN.Replace("/", "");  // 去掉斜杠;

            if (!CommonMethod.ReportMIKey(FunctionSettingNow.MIKeyReportUrl, reportMIKey, out msg))
            {
                msg = string.Format("ReportMIKey error!\r\n{0}", msg);
                Log.WriteErrorLog(msg);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 执行抄key等动作
        /// </summary>
        public void Writekey()
        {
            DateTime startTime = DateTime.Now;
            ArrayList keypath = new ArrayList();
            ArrayList keyStream = new ArrayList();
            ArrayList keyReader = new ArrayList();
            //int SerailDelay = FunctionSettingNow.SerailDelay;
            int SerailDelay = FunctionSettingNow.NextCommandWaitTime;

            Log.WriteInfoLog(SN + "   start testing");
            // 0表示抄写失败,特殊：上报IDM失败\获取key失败\抄写失败;
            // 1表示抄写成功,特殊：无;
            // 2表示抄写成功,特殊：但试产NTF要求连续2次PASS才能上传MES，需要再测试一次;
            // 3表示抄写成功,特殊：上报MES失败;
            int TestResult = 0;
            string keycontent = "";
            bool EnterFactoryResult = false;
            byte[] result;
            byte[] data;
            string error = "";
            // 报错信息;
            string ErrMsg = "";
            //进工厂
            if (!TVPort.IsOpen)
            {
                try
                {
                    TVPort.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    goto stop;
                }
            }
            for (int i = 0; i <= FunctionSettingNow.EnterFactoryRetry; i++)
            {
                if (i == 0)
                    Log.WriteInfoLog("Enter factory...");
                else
                    Log.WriteInfoLog("Retry enter factory " + i.ToString() + " ...");
                if (SerialCMD.EnterFactory(TVPort, out result, out data, out error, SerailDelay))
                {
                    EnterFactoryResult = true;
                    break;
                }
            }
            if (!EnterFactoryResult)
            {
                ErrMsg = string.Format("{0} Enter factory fail, Please check the problem", SN);
                Log.WriteErrorLog(ErrMsg);
                ShowVerifyDelegate(ErrMsg);
                goto stop;
            }

            //烧录SN
            if (WritePSN.Checked)
            {
                Log.WriteInfoLog("Write PSN");
                if (SerialCMD.SetFireTVPSN(TVPort, Encoding.ASCII.GetBytes(SN), out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writePSN);
                    Log.WriteInfoLog("Read PSN");
                    if (SerialCMD.ReadFireTVPSN(TVPort, out result, out data, out error, SerailDelay))
                    {
                        if (!Encoding.ASCII.GetString(data).Equals(SN))
                        {
                            ErrMsg = string.Format("{0} Compare PSN error!\r\n", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }

                        SetsuccessStatus(m_readPSN);
                        SetsuccessStatus(ResultStatus);
                        goto stop;
                    }
                    else
                    {
                        SetfailStatus(m_readPSN);
                        ErrMsg = string.Format("{0} Read PSN error!\r\n", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writePSN);
                    ErrMsg = string.Format("{0} Write PSN error!\r\n", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            string strACASID="";
            // 如果是要导出ACASID+SN,先判断ACASID是否等于20位长度;
            if (FunctionSettingNow.ExportSNACASID)
            {
                if (SerialCMD.ReadJapaneseACASID(TVPort, out result, out data, out error, SerailDelay))
                {
                    if (data.Length != 20)
                    {
                        SetfailStatus(m_readACASID);
                        ErrMsg = string.Format("{0} The ACAS ID length doesn't equal 20!\r\n{1}", SN, data.ToString());
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                    SetsuccessStatus(m_readACASID);
                }
                else
                {
                    SetfailStatus(m_readACASID);
                    ErrMsg = string.Format("{0} Read ACAS ID error!\r\n", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                //strACASID=data.ToString();
                strACASID = Encoding.ASCII.GetString(data);
            }

            //获取key                      
            if (midListNow.host == "LocalPC" && !preloadNow)
            {
                string Didpath = "";
                string Macpath = "";
                string Hdcppath = "";
                string Hdcp22path = "";
                string Esnpath = "";
                string MGKpath = "";
                string Widevinepath = "";
                string Cipath = "";
                string Attestationpath = "";
                string Fairplaypath = "";
                string LEKpath = "";
                string PEKpath = "";
                string Playreadypath = "";
                string Hashkeypath = "";
                string AcasKeypath = "";

                if (WriteDID.Checked)
                {
                    if (GetLocalKeyCount.GetLocalStringKeys(orderNow, "DeviceID", FunctionSettingNow.LocalDidSize, out FileStream Stream, out StreamReader Reader, out string did, out Didpath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.DID.data = did;
                        Log.WriteGetKeyLog("\r\nLocal DeviceID=" + keyInfo.DID);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Didpath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetDIDError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteMac.Checked)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "MAC", FunctionSettingNow.LocalMacSize, out FileStream Stream, out BinaryReader Reader, out string mac, out Macpath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.Mac.data = mac;
                        Log.WriteGetKeyLog("\r\nLocal Mac=" + keyInfo.Mac);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Macpath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetMacError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteHDCP.Checked)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "HDCPKEY", FunctionSettingNow.LocalHdcpSize, out FileStream Stream, out BinaryReader Reader, out string hdcp, out Hdcppath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.HDCP.data = hdcp;
                        Log.WriteGetKeyLog("\r\nLocal HDCP=" + keyInfo.HDCP);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Hdcppath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetHDCPError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteHDCP22.Checked)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "HDCPKEY22", FunctionSettingNow.LocalHdcp22Size, out FileStream Stream, out BinaryReader Reader, out string hdcp22, out Hdcp22path, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.HDCP22.data = hdcp22;
                        Log.WriteGetKeyLog("\r\nLocal HDCP22=" + keyInfo.HDCP22);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Hdcp22path);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetHDCP22Error, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteESN.Checked)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "ESN", FunctionSettingNow.LocalEsnSize, out FileStream Stream, out BinaryReader Reader, out string esn, out Esnpath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.ESN.data = esn;
                        Log.WriteGetKeyLog("\r\nLocal ESN=" + keyInfo.ESN);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Esnpath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetESNError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteMGK.Checked)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "MGK", FunctionSettingNow.LocalMGKSize, out FileStream Stream, out BinaryReader Reader, out string mgk, out MGKpath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.MGK.data = mgk;
                        Log.WriteGetKeyLog("\r\nLocal MGK=" + keyInfo.MGK);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(MGKpath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetMGKError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteFairplay.Checked)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "Fairplay", FunctionSettingNow.LocalFairplaySize, out FileStream Stream, out BinaryReader Reader, out string fairplay, out Fairplaypath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.Fairplay.data = fairplay;
                        Log.WriteGetKeyLog("\r\nLocal Fairplay=" + keyInfo.Fairplay);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Fairplaypath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetFairplayError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteWidevine.Checked)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "Widevine", FunctionSettingNow.LocalWidevineSize, out FileStream Stream, out BinaryReader Reader, out string widevine, out Widevinepath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.Widevine.data = widevine;
                        Log.WriteGetKeyLog("\r\nLocal Widevine=" + keyInfo.Widevine);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Widevinepath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetWidevineError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteCiplus.Checked)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "CIKEY", FunctionSettingNow.LocalCiSize, out FileStream Stream, out BinaryReader Reader, out string ci, out Cipath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.CI_plus.data = ci;
                        Log.WriteGetKeyLog("\r\nLocal CI_plus=" + keyInfo.CI_plus);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Cipath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetCiError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteAttestation.Checked)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "Attestation", FunctionSettingNow.LocalCiSize, out FileStream Stream, out BinaryReader Reader, out string attestation, out Attestationpath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.Attestation.data = attestation;
                        Log.WriteGetKeyLog("\r\nLocal attestation=" + keyInfo.Attestation);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Attestationpath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetAttestationError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (fireTVKey.LEK)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "LEK", -1, out FileStream Stream, out BinaryReader Reader, out string lek, out LEKpath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.LEK.data = lek;
                        Log.WriteGetKeyLog("\r\nLocal LEK=" + keyInfo.LEK);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(LEKpath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("获取LEK失败 {0}", error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (fireTVKey.PEK)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "PEK", -1, out FileStream Stream, out BinaryReader Reader, out string pek, out PEKpath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.PEK.data = pek;
                        Log.WriteGetKeyLog("\r\nLocal LEK=" + keyInfo.PEK);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(PEKpath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("获取PEK失败{0}", error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (fireTVKey.Playready)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "Playready", -1, out FileStream Stream, out BinaryReader Reader, out string playready, out Playreadypath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.Playready.data = playready;
                        Log.WriteGetKeyLog("\r\nLocal Playready=" + keyInfo.Playready);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Playreadypath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("获取Playready失败{0}", error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (fireTVKey.Hashkey)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "Hashkey", -1, out FileStream Stream, out BinaryReader Reader, out string hashkey, out Hashkeypath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.Hashkey.data = hashkey;
                        Log.WriteGetKeyLog("\r\nLocal Hashkey=" + keyInfo.Hashkey);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(Fairplaypath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("获取hashkey失败 {0}", error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteACASKey.Checked)
                {
                    if (GetLocalKeyCount.GetLocalHexKeys(orderNow, "ACAS_KEY", FunctionSettingNow.localACASKeySize, out FileStream Stream, out BinaryReader Reader, out string acaskey, out AcasKeypath, out error, errorDBNow, ref localmidList, SN))
                    {
                        keyInfo.ACASKey_Data.data = acaskey;
                        Log.WriteGetKeyLog("\r\nLocal ACASKey=" + keyInfo.ACASKey_Data);
                        if (Stream != null && Reader != null)
                        {
                            keypath.Add(AcasKeypath);
                            keyStream.Add(Stream);
                            keyReader.Add(Reader);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0} {1}", LResource.GetACASKeyError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteEDIDPID.Checked)
                {
                    keyInfo.EDIDPid.data = midListNow.keytype["edid_pid"];
                }
                if (WriteEDIDName.Checked)
                {
                    keyInfo.EDIDModelName.data = midListNow.keytype["edid_model_name"];
                }
                if (localmidList.host != null)
                {
                    if (ClientTypeText.Text.Length == 0)
                    {
                        SetTextStatus(ClientTypeText, localmidList.clienttype);
                    }
                    if (SVText.Text.Length == 0)
                    {
                        SetTextStatus(SVText, localmidList.version);
                    }
                    if (ProjectIDText.Text.Length == 0)
                    {
                        SetTextStatus(ProjectIDText, localmidList.projectid);
                    }
                }
            }
            else if (!preloadNow)
            {
                // 计算获取全部key耗时;
                Stopwatch watch = new Stopwatch();
                watch.Start();
                if (WriteDID.Checked)
                {
                    if (CommonMethod.GetKeys(midListNow.host, "DeviceID", SN, "devicetype=tcl_unknown_model", errorDBNow, out string did, out error, orderNow, out string md5))
                    {
                        keyInfo.DID.data = did;
                        Log.WriteGetKeyLog("\r\nDeviceID=" + keyInfo.DID);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetDIDError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteMac.Checked && midListNow.keytype.ContainsKey("MAC"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "MAC", SN, midListNow.keytype["MAC"], errorDBNow, out string mac, out error, orderNow, out string md5))
                    {
                        keyInfo.Mac.data = mac;
                        Log.WriteGetKeyLog("\r\nMac=" + keyInfo.Mac);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetMacError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteHDCP.Checked && midListNow.keytype.ContainsKey("HDCP_KEY"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "HDCP_KEY", SN, midListNow.keytype["HDCP_KEY"], errorDBNow, out string hdcp, out error, orderNow, out string md5))
                    {
                        keyInfo.HDCP.data = hdcp;
                        Log.WriteGetKeyLog("\r\nHDCP=" + keyInfo.HDCP);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetHDCPError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteHDCP22.Checked && midListNow.keytype.ContainsKey("HDCP2.2_KEY"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "HDCP2.2_KEY", SN, midListNow.keytype["HDCP2.2_KEY"], errorDBNow, out string hdcp22, out error, orderNow, out string md5))
                    {
                        keyInfo.HDCP22.data = hdcp22;
                        Log.WriteGetKeyLog("\r\nHDCP22=" + keyInfo.HDCP22);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetHDCP22Error, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteESN.Checked  && midListNow.keytype.ContainsKey("NETFILX_ESN"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "NETFILX_ESN", SN, midListNow.keytype["NETFILX_ESN"], errorDBNow, out string esn, out error, orderNow, out string md5))
                    {
                        keyInfo.ESN.data = esn;
                        Log.WriteGetKeyLog("\r\nESN=" + keyInfo.ESN);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetESNError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteWiDi.Checked && midListNow.keytype.ContainsKey("WiDi"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "WiDi", SN, midListNow.keytype["WiDi"], errorDBNow, out string widi, out error, orderNow, out string md5))
                    {
                        keyInfo.WiDi.data = widi;
                        Log.WriteGetKeyLog("\r\nWiDi=" + keyInfo.WiDi);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetWiDiError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteCiplus.Checked && midListNow.keytype.ContainsKey("CI_PLUS_KEY"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "CI_PLUS_KEY", SN, midListNow.keytype["CI_PLUS_KEY"], errorDBNow, out string ci, out error, orderNow, out string md5))
                    {
                        keyInfo.CI_plus.data = ci;
                        Log.WriteGetKeyLog("\r\nCI_plus=" + keyInfo.CI_plus);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetCiError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteWidevine.Checked && midListNow.keytype.ContainsKey("Widevine_KEY"))
                {
                    if (CommonMethod.GetWidevineAnAttestationKey(
                        midListNow.host,
                        SN,
                        midListNow.keytype["Widevine_KEY"],
                        errorDBNow,
                        out bool isAndroidTV,
                        out string widevine,
                        out string attestation,
                        out error,
                        orderNow,
                        out string md5))
                    {
                        keyInfo.Widevine.data = widevine;
                        Log.WriteGetKeyLog("\r\nWidevine=" + keyInfo.Widevine);

                        if (isAndroidTV)
                        {
                            keyInfo.Attestation.data = attestation;
                            keyInfo.AttestationMD5.data = md5;
                            Log.WriteGetKeyLog("\r\nAttestationMD5=" + keyInfo.AttestationMD5);
                        }
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetWidevineError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteMGK.Checked && midListNow.keytype.ContainsKey("MGK_KEY"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "MGK_KEY", SN, midListNow.keytype["MGK_KEY"], errorDBNow, out string mgk, out error, orderNow, out string md5))
                    {
                        keyInfo.MGK.data = mgk;
                        Log.WriteGetKeyLog("\r\nMGK=" + keyInfo.MGK);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetMGKError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteFairplay.Checked && midListNow.keytype.ContainsKey("Fairplay_KEY"))
                {
                    //if (!CommonMethod.GetIDMKeys(midListNow.host, SN, orderNow, psn, devicecode, key2Write, errorDBNow, ref keyInfo, out error))
                    if (!V2Method.GetMidKey(midListNow.host, SN, orderNow, psn, devicecode, key2Write, errorDBNow, ref keyInfo, out error))
                    {
                        keyInfo.Fairplay.data = fairplay;
                        Log.WriteGetKeyLog("\r\nFairplay=" + keyInfo.Fairplay);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetFairplayError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteWifiMac.Checked && midListNow.keytype.ContainsKey("MAC"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "MAC", "WiFi_MAC" + SN, midListNow.keytype["MAC"], errorDBNow, out string mac, out error, orderNow, out string md5))
                    {
                        keyInfo.WiFi_MAC.data = mac;
                        Log.WriteGetKeyLog("\r\nWiFi_MAC=" + keyInfo.WiFi_MAC);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetMacError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteBTMac.Checked && midListNow.keytype.ContainsKey("MAC"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "MAC", "BT_MAC" + SN, midListNow.keytype["MAC"], errorDBNow, out string mac, out error, orderNow, out string md5))
                    {
                        keyInfo.BT_MAC.data = mac;
                        Log.WriteGetKeyLog("\r\nBT_MAC=" + keyInfo.BT_MAC);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetMacError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteECP.Checked && midListNow.keytype.ContainsKey("ECP_KEY"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "ECP_KEY", SN, midListNow.keytype["ECP_KEY"], errorDBNow, out string ecp, out error, orderNow, out string md5))
                    {
                        keyInfo.ECP.data = ecp;
                        Log.WriteGetKeyLog("\r\nECP_KEY=" + keyInfo.ECP);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetECPError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteLEK.Checked && midListNow.keytype.ContainsKey("LEK"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "LEK", SN, midListNow.keytype["LEK"], errorDBNow, out string lek, out error, orderNow, out string md5))
                    {
                        keyInfo.LEK.data = lek;
                        Log.WriteGetKeyLog("\r\nLEK=" + keyInfo.LEK);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetLEKError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WritePEK.Checked && midListNow.keytype.ContainsKey("PEK"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "PEK", SN, midListNow.keytype["PEK"], errorDBNow, out string pek, out error, orderNow, out string md5))
                    {
                        keyInfo.PEK.data = pek;
                        Log.WriteGetKeyLog("\r\nPEK=" + keyInfo.PEK);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetPEKError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WritePlayready.Checked && midListNow.keytype.ContainsKey("PlayReady_key"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "PlayReady_key", SN, midListNow.keytype["PlayReady_key"], errorDBNow, out string playready, out error, orderNow, out string md5))
                    {
                        keyInfo.Playready.data = playready;
                        Log.WriteGetKeyLog("\r\nPlayReady_key=" + keyInfo.Playready);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetPlayreadyError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteHash.Checked && midListNow.keytype.ContainsKey("Hashkey"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "Hashkey", SN, midListNow.keytype["Hashkey"], errorDBNow, out string hash, out error, orderNow, out string md5))
                    {
                        keyInfo.Hashkey.data = hash;
                        Log.WriteGetKeyLog("\r\nHashkey=" + keyInfo.Hashkey);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetHashkeyError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteYouTube.Checked && midListNow.keytype.ContainsKey("YouTube_KEY"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "YouTube_KEY", SN, midListNow.keytype["YouTube_KEY"], errorDBNow, out string youtube, out error, orderNow, out string md5))
                    {
                        keyInfo.YouTube_KEY.data = youtube;
                        Log.WriteGetKeyLog("\r\nYouTube_KEY=" + keyInfo.YouTube_KEY);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetYouTubekeyError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteEDIDPID.Checked && midListNow.keytype.ContainsKey("edid_pid"))
                {
                    keyInfo.EDIDPid.data = midListNow.keytype["edid_pid"];
                }
                if (WriteEDIDName.Checked && midListNow.keytype.ContainsKey("edid_model_name"))
                {
                    keyInfo.EDIDModelName.data = midListNow.keytype["edid_model_name"];
                }
                if (WriteACASKey.Checked && midListNow.keytype.ContainsKey("ACAS_KEY"))
                {
                    if (CommonMethod.GetAcasKey(midListNow.host, "ACAS_KEY", SN, midListNow.keytype["ACAS_KEY"], errorDBNow, orderNow, out string acaskey_data, out string acaskey_datamd5, out string acaskey_tool, out string acaskey_toolmd5, out error))
                    {
                        keyInfo.ACASKey_Data.data = acaskey_data;
                        keyInfo.ACASKey_DataMd5.data = acaskey_datamd5;

                        keyInfo.ACASKey_Tool.data = acaskey_tool;
                        keyInfo.ACASKey_ToolMd5.data = acaskey_toolmd5;

                        Log.WriteGetKeyLog("\r\nACAS_KEY_DATA=" + keyInfo.ACASKey_Data.data + "\r\nACAS_KEY_MD5=" + keyInfo.ACASKey_DataMd5);
                        Log.WriteGetKeyLog("\r\nACAS_KEY_TOOL=" + keyInfo.ACASKey_Tool.data + "\r\nACAS_KEY_TOOLMD5=" + keyInfo.ACASKey_ToolMd5);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetACASKeyError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                if (WriteDAK.Checked && midListNow.keytype.ContainsKey("DAK"))
                {
                    if (CommonMethod.GetKeys(midListNow.host, "DAK", SN, midListNow.keytype["DAK"], errorDBNow, out string hash, out error, orderNow, out string md5))
                    {
                        keyInfo.DAK.data = hash;
                        Log.WriteGetKeyLog("\r\nDAK=" + keyInfo.DAK);
                    }
                    else
                    {
                        ErrMsg = String.Format("{0}\r\n{1}", LResource.GetDAKKeyError, error);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                watch.Stop();
                Log.WriteInfoLog(string.Format("Get All Keys Elapsed={0}", watch.Elapsed.TotalMilliseconds));
            }

            #region 小米FireTV功能启用;
            if (FunctionSettingNow.MITVEnable)
            {
                // 获取Key;
                if (!CommonMethod.GetMIKey(FunctionSettingNow.MIKeyUrl, SN, out _MiKey, out error))
                {
                    ErrMsg = string.Format("GetMIKey error!\r\n{0}", error);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                // 配置要抄写的选项;
                if (_MiKey.EthernetMac != null)
                {
                    SetCheckboxStatus(WriteMac, true);
                    keyInfo.Mac.data = _MiKey.EthernetMac;
                    keyInfo.Mac.enable = true;
                }
                else if ( !midListNow.keytype.ContainsKey("MAC") )
                {
                    SetCheckboxStatus(WriteMac, false);
                }

                if (_MiKey.BTMac != null)
                {
                    SetCheckboxStatus(WriteBTMac, true);
                    keyInfo.BT_MAC.data = _MiKey.BTMac;
                    keyInfo.BT_MAC.enable = true;
                }
                else if (!midListNow.keytype.ContainsKey("BT_MAC"))
                {
                    SetCheckboxStatus(WriteBTMac, false);
                }

                if (_MiKey.DSN != null)
                {
                    SetCheckboxStatus(WriteDSN, true);
                    keyInfo.DSN.data = _MiKey.DSN;
                    keyInfo.DSN.enable = true;
                }
                else if (!midListNow.keytype.ContainsKey("DSN"))
                {
                    SetCheckboxStatus(WriteDSN, false);
                }

                if (_MiKey.WIFIMAC != null)
                {
                    SetCheckboxStatus(WriteWifiMac, true);
                    keyInfo.WiFi_MAC.data = _MiKey.WIFIMAC;
                    keyInfo.WiFi_MAC.enable = true;
                }
                else if (!midListNow.keytype.ContainsKey("WiFi_MAC"))
                {
                    SetCheckboxStatus(WriteWifiMac, false);
                }
            }
            #endregion

            #region 开始抄写;
            // 如果是抄写EDID,则不获取白平衡数据;
            if (CommonMethod.IsEDIDCopy(midListNow))
            {
                SetspecificText(SoftwareVersionNote, LResource.SkipChecking, Color.Yellow);
                SetspecificText(ClientTypeNote, LResource.SkipChecking, Color.Yellow);
                if (midListNow.projectid.Equals("0"))
                    SetspecificText(ProjectIDNote, LResource.SkipCovering, Color.Yellow);
            }

            //检查Software version
            if (SoftwareVersionNote.Text != LResource.SkipChecking)
            {
                Log.WriteInfoLog("Check software version...\r\n");
                if (SerialCMD.GetSoftVersion(TVPort, out result, out data, out error, SerailDelay))
                {
                    string sfv = Encoding.ASCII.GetString(data);
                    if (sfv != SVText.Text)
                    {
                        MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                        DialogResult dr = MessageBox.Show(LResource.MainboardFV + sfv + LResource.differentfromserver + SVText.Text + "\r\n" + LResource.SkipFVChecking, LResource.Error, messButton);
                        if (dr == DialogResult.OK)
                        {
                            SetspecificText(SoftwareVersionNote, LResource.SkipChecking, Color.Yellow);
                            SetcolorStatus(SVText, Color.Yellow);
                        }
                        else
                        {
                            SetspecificText(SoftwareVersionNote, sfv, Color.Red);
                            SetcolorStatus(SVText, Color.Red);
                            goto end;
                        }
                    }
                    else
                    {
                        SetcolorStatus(SVText, Color.FromArgb(128, 255, 128));
                    }
                }
                else
                {
                    ErrMsg = string.Format("{0} Read software version fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            //DID抄写
            if (WriteDID.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.DID.data))
                {
                    ErrMsg = string.Format("DID format error!\r\n{0}", keyInfo.DID.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] DIDData = Encoding.ASCII.GetBytes(keyInfo.DID.data);
                Log.WriteInfoLog("Write DID...");
                if (SerialCMD.SetDeviceID(TVPort, DIDData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writedid);
                    Log.WriteInfoLog("Check DID...");
                    if (cfg_writecheck.DIDCheckcheck ? SerialCMD.CheckDeviceId(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkdid);
                        Log.WriteInfoLog("Read DID...");
                        if (cfg_readcheck.DIDReadcheck ? SerialCMD.GetDeviceId(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.DIDReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, DIDData))
                                {
                                    SetsuccessStatus(m_readdid);
                                }
                                else
                                {
                                    SetfailStatus(m_readdid);
                                    ErrMsg = string.Format("{0} contrast DID fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end; ;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readdid);
                            ErrMsg = string.Format("{0} read DID fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkdid);
                        ErrMsg = string.Format("{0} check DID fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writedid);
                    ErrMsg = string.Format("{0} Write DID fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.DID.result = true;
            }

            //Eth_Mac抄写
            if (WriteMac.Checked)
            {
                string mac = keyInfo.Mac.data.Replace("-", "");
                if (FunctionSettingNow.MITVEnable == true)
                    mac = keyInfo.Mac.data.Replace(":", "");
                if (!CommonMethod.IsNumberAndWord(mac))
                {
                    ErrMsg = string.Format("Mac format error!\r\n{0}", mac);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] MacData = SerialInit.HexToByte(mac);
                Log.WriteInfoLog("Write Mac...");
                if (SerialCMD.SetMAC(TVPort, MacData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writemac);
                    Log.WriteInfoLog("Check Mac...");
                    if (cfg_writecheck.MacCheckcheck ? SerialCMD.CheckMAC(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkmac);
                        Log.WriteInfoLog("Read Mac...");
                        if (cfg_readcheck.MacReadcheck ? SerialCMD.GetMAC(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.MacReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, MacData))
                                {
                                    SetsuccessStatus(m_readmac);
                                }
                                else
                                {
                                    SetfailStatus(m_readmac);
                                    ErrMsg = string.Format("{0}  contrast Mac fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readmac);
                            ErrMsg = string.Format("{0}  read Mac fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkmac);
                        ErrMsg = string.Format("{0}  check Mac fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writemac);
                    ErrMsg = string.Format("{0}  Write Mac fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.Mac.result = true;
            }

            //WiFi_MAC抄写
            if (WriteWifiMac.Checked)
            {
                string wifimac = keyInfo.WiFi_MAC.data.Replace("-", "");
                if (FunctionSettingNow.MITVEnable == true)
                    wifimac = wifimac.Replace(":", "");
                if (!CommonMethod.IsNumberAndWord(wifimac))
                {
                    ErrMsg = string.Format("Wifi Mac format error!\r\n{0}", wifimac);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] WifiMacData = Encoding.ASCII.GetBytes(wifimac);
                Log.WriteInfoLog("Write WifiMac...");
                if (SerialCMD.SetFireTVWifiMac(TVPort, WifiMacData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeWifiMac);
                    Log.WriteInfoLog("Check WifiMac...");
                    if (cfg_writecheck.WifiMacCheckcheck ? SerialCMD.CheckFireTVWifiMac(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkWifiMac);
                        Log.WriteInfoLog("Read WifiMac...");
                        if (cfg_readcheck.WifiMacReadcheck ? SerialCMD.GetFireTVWiFi_Mac(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.WifiMacReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, WifiMacData))
                                {
                                    SetsuccessStatus(m_readWifiMac);
                                }
                                else
                                {
                                    SetfailStatus(m_readWifiMac);
                                    ErrMsg = string.Format("{0}  contrast Wifi Mac fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readWifiMac);
                            ErrMsg = string.Format("{0}  read Wifi Mac fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkWifiMac);
                        ErrMsg = string.Format("{0}  check Wifi Mac fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeWifiMac);
                    ErrMsg = string.Format("{0}  Write Wifi Mac fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.WiFi_MAC.result = true;
            }

            //BT_MAC抄写
            if (WriteBTMac.Checked)
            {
                string btmac = keyInfo.BT_MAC.data.Replace("-", "");
                if (FunctionSettingNow.MITVEnable == true)
                    btmac = btmac.Replace(":", "");
                if (!CommonMethod.IsNumberAndWord(btmac))
                {
                    ErrMsg = string.Format("BTMac format error!\r\n{0}", btmac);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] BTMacData = Encoding.ASCII.GetBytes(btmac);
                Log.WriteInfoLog("Write BTMac...");
                if (SerialCMD.SetFireTVBTMac(TVPort, BTMacData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeBTMac);
                    Log.WriteInfoLog("Check BTMac...");
                    if (cfg_writecheck.BTMacCheckcheck ? SerialCMD.CheckFireTVBTMac(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkBTMac);
                        Log.WriteInfoLog("Read BTMac...");
                        if (cfg_readcheck.BTMacReadcheck ? SerialCMD.GetFireTVBT_Mac(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.BTMacReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, BTMacData))
                                {
                                    SetsuccessStatus(m_readBTMac);
                                }
                                else
                                {
                                    SetfailStatus(m_readBTMac);
                                    ErrMsg = string.Format("{0}  contrast BT Mac fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readBTMac);
                            ErrMsg = string.Format("{0}  read BT Mac fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkBTMac);
                        ErrMsg = string.Format("{0}  check BT Mac fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeBTMac);
                    ErrMsg = string.Format("{0}  Write BT Mac fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.BT_MAC.result = true;
            }

            //PEK抄写
            if (WritePEK.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.PEK.data))
                {
                    ErrMsg = string.Format("PEK format error!\r\n{0}", keyInfo.PEK.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                byte[] PEKData = SerialInit.HexToByte(keyInfo.PEK.data);
                Log.WriteInfoLog("Write PEK...");
                if (SerialCMD.SetFireTVPEK(TVPort, PEKData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writePEK);
                    Log.WriteInfoLog("Check PEK...");
                    if (cfg_writecheck.PEKCheckcheck ? SerialCMD.CheckFireTVPEK(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkPEK);
                        Log.WriteInfoLog("Read PEK...");
                        if (cfg_readcheck.PEKReadcheck ? SerialCMD.ReadFireTVPEK(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.PEKReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, PEKData))
                                {
                                    SetsuccessStatus(m_readPEK);
                                }
                                else
                                {
                                    SetfailStatus(m_readPEK);
                                    ErrMsg = string.Format("{0}  contrast PEK fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readPEK);
                            ErrMsg = string.Format("{0}  read PEK fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkPEK);
                        ErrMsg = string.Format("{0}  check PEK fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writePEK);
                    ErrMsg = string.Format("{0}  Write PEK fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.PEK.result = true;
            }

            // DAK 抄写;
            if (WriteDAK.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.DAK.data))
                {
                    ErrMsg = string.Format("DAK format error!\r\n{0}", keyInfo.DAK.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] DAKData = SerialInit.HexToByte(keyInfo.DAK.data);
                Log.WriteInfoLog("Write DAK...");
                if (SerialCMD.SetFireTVDAK(TVPort, DAKData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeDAK);
                    Log.WriteInfoLog("Check DAK...");
                    if (cfg_writecheck.DAKCheckcheck ? SerialCMD.CheckFireTVDAK(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkDAK);
                    }
                    else
                    {
                        SetfailStatus(m_checkDAK);
                        ErrMsg = string.Format("{0}  check DAK fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeDAK);
                    ErrMsg = string.Format("{0}  Write DAK fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.DAK.result = true;
            }

            //LEK抄写
            if (WriteLEK.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.LEK.data))
                {
                    ErrMsg = string.Format("LEK format error!\r\n{0}", keyInfo.LEK.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] LEKData = SerialInit.HexToByte(keyInfo.LEK.data);
                Log.WriteInfoLog("Write LEK...");
                if (SerialCMD.SetFireTVLEK(TVPort, LEKData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeLEK);
                    Log.WriteInfoLog("Check LEK...");
                    if (cfg_writecheck.LEKCheckcheck ? SerialCMD.CheckFireTVLEK(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkLEK);
                        Log.WriteInfoLog("Read LEK...");
                        if (cfg_readcheck.LEKReadcheck ? SerialCMD.ReadFireTVLEK(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.LEKReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, LEKData))
                                {
                                    SetsuccessStatus(m_readLEK);
                                }
                                else
                                {
                                    SetfailStatus(m_readLEK);
                                    ErrMsg = string.Format("{0}  contrast LEK fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readLEK);
                            ErrMsg = string.Format("{0}  read LEK fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkLEK);
                        ErrMsg = string.Format("{0}  check LEK fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeLEK);
                    ErrMsg = string.Format("{0}  Write LEK fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.LEK.result = true;
            }

            //HDCP KEY抄写
            if (WriteHDCP.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.HDCP.data))
                {
                    ErrMsg = string.Format("HDCP format error!\r\n{0}", keyInfo.HDCP.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] HDCPData = SerialInit.HexToByte(keyInfo.HDCP.data);
                Log.WriteInfoLog("Write HDCP...");
                if (SerialCMD.SetHDCPKey(TVPort, HDCPData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writehdcp);
                    Log.WriteInfoLog("Check HDCP...");
                    if (cfg_writecheck.HDCPCheckcheck ? SerialCMD.CheckHDCP(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkhdcp);
                        Log.WriteInfoLog("Read HDCP...");
                        if (cfg_readcheck.HDCPReadcheck ? SerialCMD.GetHDCPKey(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.HDCPReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, HDCPData))
                                {
                                    SetsuccessStatus(m_readhdcp);
                                }
                                else
                                {
                                    SetfailStatus(m_readhdcp);
                                    ErrMsg = string.Format("{0}  contrast HDCP fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }

                        }
                        else
                        {
                            SetfailStatus(m_readhdcp);
                            ErrMsg = string.Format("{0}  read HDCP fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkhdcp);
                        ErrMsg = string.Format("{0}  check HDCP fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writehdcp);
                    ErrMsg = string.Format("{0}  Write HDCP fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.HDCP.result = true;
            }

            //HDCP22 KEY抄写
            if (WriteHDCP22.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.HDCP22.data))
                {
                    ErrMsg = string.Format("HDCP22 format error!\r\n{0}", keyInfo.HDCP22.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                byte[] HDCP22Data = SerialInit.HexToByte(keyInfo.HDCP22.data);
                Log.WriteInfoLog("Write HDCP22...");
                if (SerialCMD.SetHDCPKey22(TVPort, HDCP22Data, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writehdcp22);
                    Log.WriteInfoLog("Check HDCP22...");
                    if (cfg_writecheck.HDCP22Checkcheck ? SerialCMD.CheckHDCP22(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkhdcp22);
                        Log.WriteInfoLog("Read HDCP22...");
                        if (cfg_readcheck.HDCP22Readcheck ? SerialCMD.GetHDCPKey22(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.HDCP22Readcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, HDCP22Data))
                                {
                                    SetsuccessStatus(m_readhdcp22);
                                }
                                else
                                {
                                    SetfailStatus(m_readhdcp22);
                                    ErrMsg = string.Format("{0}  contrast HDCP22 fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readhdcp22);
                            ErrMsg = string.Format("{0}  read HDCP22 fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkhdcp22);
                        ErrMsg = string.Format("{0}  check HDCP22 fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writehdcp22);
                    ErrMsg = string.Format("{0}  Write HDCP22 fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.HDCP22.result = true;
            }

            //ESN KEY抄写
            if (WriteESN.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.ESN.data))
                {
                    ErrMsg = string.Format("ESN format error!\r\n{0}", keyInfo.ESN.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                byte[] ESNData = SerialInit.HexToByte(keyInfo.ESN.data);
                Log.WriteInfoLog("Write ESN...");
                if (SerialCMD.SetNetflixESN(TVPort, ESNData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeesn);
                    Log.WriteInfoLog("Check ESN...");
                    if (cfg_writecheck.ESNCheckcheck ? SerialCMD.CheckNetflixESN(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkesn);
                        Log.WriteInfoLog("Read ESN...");
                        if (cfg_readcheck.ESNReadcheck ? SerialCMD.GetNetflixESN(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.ESNReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, ESNData))
                                {
                                    SetsuccessStatus(m_readesn);
                                }
                                else
                                {
                                    SetfailStatus(m_readesn);
                                    ErrMsg = string.Format("{0}  contrast ESN fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }

                        }
                        else
                        {
                            SetfailStatus(m_readesn);
                            ErrMsg = string.Format("{0}  read ESN fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkesn);
                        ErrMsg = string.Format("{0}  check ESN fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeesn);
                    ErrMsg = string.Format("{0}  Write ESN fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            //Youtube key抄写
            if (WriteYouTube.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.YouTube_KEY.data))
                {
                    ErrMsg = string.Format("YouTube format error!\r\n{0}", keyInfo.YouTube_KEY.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                byte[] YouTubeData = SerialInit.HexToByte(keyInfo.YouTube_KEY.data);
                Log.WriteInfoLog("Write YouTube key...");
                if (SerialCMD.SetFireTVYoutube(TVPort, YouTubeData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeYouTube);
                    Log.WriteInfoLog("Check YouTube_KEY...");
                    if (cfg_writecheck.YouTubeCheckcheck ? SerialCMD.CheckFireTVYoutube(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkYouTube);
                        Log.WriteInfoLog("Read YouTube_KEY...");
                        if (cfg_readcheck.YouTubeReadcheck ? SerialCMD.ReadFireTVYoutube(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.YouTubeReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, YouTubeData))
                                {
                                    SetsuccessStatus(m_readYouTube);
                                }
                                else
                                {
                                    SetfailStatus(m_readYouTube);
                                    ErrMsg = string.Format("{0}  contrast YouTube_KEY fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readYouTube);
                            ErrMsg = string.Format("{0}  read YouTube_KEY fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkYouTube);
                        ErrMsg = string.Format("{0}  check YouTube_KEY fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeYouTube);
                    ErrMsg = string.Format("{0}  Write YouTube_KEY fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.YouTube_KEY.result = true;
            }

            //Widevine KEY抄写
            if (WriteWidevine.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.Widevine.data))
                {
                    ErrMsg = string.Format("Widevine format error!\r\n{0}", keyInfo.Widevine.data);
                    Log.WriteErrorLog(ErrMsg);
                    //MessageBox.Show(LResource.WidevineFormatError + "\r\n" + keyInfo.Widevine);
                    goto end;
                }
                byte[] WidevineData = SerialInit.HexToByte(keyInfo.Widevine.data);
                Log.WriteInfoLog("Write Widevine...");
                if (SerialCMD.SetWidevine(TVPort, WidevineData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writewidevine);
                    Log.WriteInfoLog("Check Widevine...");
                    if (cfg_writecheck.WidevineCheckcheck ? SerialCMD.CheckWidevine(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkwidevine);
                        Log.WriteInfoLog("Read Widevine...");
                        if (cfg_readcheck.WidevineReadcheck ? SerialCMD.GetWidevine(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.WidevineReadcheck)
                            {
                                if (CommonMethod.CompareMD5(WidevineData, data))
                                {
                                    SetsuccessStatus(m_readwidevine);
                                }
                                else
                                {
                                    if (SerialInit.BytesCompare_Base64(data, WidevineData))
                                    {
                                        SetsuccessStatus(m_readwidevine);
                                    }
                                    else
                                    {
                                        SetfailStatus(m_readwidevine);
                                        ErrMsg = string.Format("{0}  contrast Widevine fail!", SN);
                                        Log.WriteErrorLog(ErrMsg);
                                        goto end;
                                    }
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readwidevine);
                            ErrMsg = string.Format("{0}  read Widevine fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkwidevine);
                        ErrMsg = string.Format("{0}  check Widevine fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writewidevine);
                    ErrMsg = string.Format("{0}  Write Widevine fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.Widevine.result = true;
            }

            //CI plus KEY抄写
            if (WriteCiplus.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.CI_plus.data))
                {
                    ErrMsg = string.Format("CI_plus format error!\r\n{0}", keyInfo.CI_plus.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                byte[] CiplusData = SerialInit.HexToByte(keyInfo.CI_plus.data);
                Log.WriteInfoLog("Write CI plus...");
                if (SerialCMD.SetCiKey(TVPort, CiplusData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeci);
                    Log.WriteInfoLog("Check CI plus...");
                    if (cfg_writecheck.CI_plusCheckcheck ? SerialCMD.CheckCikey(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkci);
                        Log.WriteInfoLog("Read CI plus...");
                        if (cfg_readcheck.CI_plusReadcheck ? SerialCMD.GetCiKey(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.CI_plusReadcheck)
                            {
                                if (CommonMethod.CompareMD5(CiplusData, data))
                                {
                                    SetsuccessStatus(m_readci);
                                }
                                else
                                {
                                    if (SerialInit.BytesCompare_Base64(data, CiplusData))
                                    {
                                        SetsuccessStatus(m_readci);
                                    }
                                    else
                                    {
                                        SetfailStatus(m_readci);
                                        ErrMsg = string.Format("{0}  contrast CI plus fail!", SN);
                                        Log.WriteErrorLog(ErrMsg);
                                        goto end;
                                    }
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readci);
                            ErrMsg = string.Format("{0}  read CI plus fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkci);
                        ErrMsg = string.Format("{0}  check CI plus fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeci);
                    ErrMsg = string.Format("{0}  Write CI plus fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.CI_plus.result = true;
            }

            //Attestation KEY抄写
            if (WriteAttestation.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.Attestation.data))
                {
                    ErrMsg = string.Format("Attestation key format error!\r\n{0}", keyInfo.Attestation.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] AttestationData = SerialInit.HexToByte(keyInfo.Attestation.data);
                Log.WriteInfoLog("Write Attestation key...");
                if (SerialCMD.SetAttestationKey(TVPort, AttestationData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeattestation);
                    Log.WriteInfoLog("Check Attestation key...");
                    if (cfg_writecheck.AttestationCheckcheck ? SerialCMD.CheckAttestationKey(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkattestation);
                        Log.WriteInfoLog("Read Attestation key...");
                        if (cfg_readcheck.AttestationReadcheck ? SerialCMD.GetAttestationKey(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.AttestationReadcheck)
                            {
                                if (CommonMethod.CompareMD5(AttestationData, data))
                                {
                                    SetsuccessStatus(m_readattestation);
                                }
                                else
                                {
                                    if (SerialInit.BytesCompare_Base64(data, AttestationData))
                                    {
                                        SetsuccessStatus(m_readattestation);
                                    }
                                    else
                                    {
                                        SetfailStatus(m_readattestation);
                                        ErrMsg = string.Format("{0}  contrast Attestation key fail!", SN);
                                        Log.WriteErrorLog(ErrMsg);
                                        goto end;
                                    }
                                }

                            }
                        }
                        else
                        {
                            SetfailStatus(m_readattestation);
                            ErrMsg = string.Format("{0}  read Attestation key fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkattestation);
                        ErrMsg = string.Format("{0}  check Attestation key fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeattestation);
                    ErrMsg = string.Format("{0}  Write Attestation key fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.Attestation.result = true;
            }

            //MGK KEY抄写
            if (WriteMGK.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.MGK.data))
                {
                    ErrMsg = string.Format("MGK format error!\r\n{0}", keyInfo.MGK.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] MGKData = SerialInit.HexToByte(keyInfo.MGK.data);
                Log.WriteInfoLog("Write MGK...");
                if (SerialCMD.SetMGKKey(TVPort, MGKData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeMGK);
                    Log.WriteInfoLog("Check MGK...");
                    if (cfg_writecheck.MGKCheckcheck ? SerialCMD.CheckMGKkey(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkMGK);
                        Log.WriteInfoLog("Read MGK...");
                        if (cfg_readcheck.MGKReadcheck ? SerialCMD.GetMGKKey(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.MGKReadcheck)
                            {
                                if (CommonMethod.CompareMD5(MGKData, data))
                                {
                                    SetsuccessStatus(m_readMGK);
                                }
                                else
                                {
                                    if (SerialInit.BytesCompare_Base64(data, MGKData))
                                    {
                                        SetsuccessStatus(m_readMGK);
                                    }
                                    else
                                    {
                                        SetfailStatus(m_readMGK);
                                        ErrMsg = string.Format("{0}  contrast MGK fail!", SN);
                                        Log.WriteErrorLog(ErrMsg);
                                        goto end;
                                    }
                                }

                            }

                        }
                        else
                        {
                            SetfailStatus(m_readMGK);
                            ErrMsg = string.Format("{0}  read MGK fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkMGK);
                        ErrMsg = string.Format("{0}  check MGK fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeMGK);
                    ErrMsg = string.Format("{0}  Write MGK fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.MGK.result = true;
            }

            //Fairplay KEY抄写
            if (WriteFairplay.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.Fairplay.data))
                {
                    ErrMsg = string.Format("Fairplay format error!\r\n{0}", keyInfo.Fairplay.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] FairplayData = SerialInit.HexToByte(keyInfo.Fairplay.data);
                Log.WriteInfoLog("Write Fairplay...");
                if (SerialCMD.SetFireTVFairplay(TVPort, FairplayData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeFairplay);
                    Log.WriteInfoLog("Check Fairplay...");
                    if (cfg_writecheck.FairplayCheckcheck ? SerialCMD.CheckFireTVFairplay(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkFairplay);
                        Log.WriteInfoLog("Read Fairplay...");
                        if (cfg_readcheck.FairplayReadcheck ? SerialCMD.ReadFireTVFairplay(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.FairplayReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, FairplayData))
                                {
                                    SetsuccessStatus(m_readFairplay);
                                }
                                else
                                {
                                    SetfailStatus(m_readFairplay);
                                    ErrMsg = string.Format("{0}  contrast Fairplay fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readFairplay);
                            ErrMsg = string.Format("{0}  read Fairplay fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkFairplay);
                        ErrMsg = string.Format("{0}  check Fairplay fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeFairplay);
                    ErrMsg = string.Format("{0}  Write Fairplay fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.Fairplay.result = true;
            }

            //ECP KEY抄写
            if (WriteECP.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.ECP.data))
                {
                    ErrMsg = string.Format("ECP format error!\r\n{0}", keyInfo.ECP.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] ECPData = SerialInit.HexToByte(keyInfo.ECP.data);
                Log.WriteInfoLog("Write ECP...");
                if (SerialCMD.SetECP(TVPort, ECPData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeECP);
                    Log.WriteInfoLog("Check ECP...");
                    if (cfg_writecheck.ECPCheckcheck ? SerialCMD.CheckECP(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkECP);
                        Log.WriteInfoLog("Read ECP...");
                        if (cfg_readcheck.ECPReadcheck ? SerialCMD.GetECP(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.ECPReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, ECPData))
                                {
                                    SetsuccessStatus(m_readECP);
                                }
                                else
                                {
                                    SetfailStatus(m_readECP);
                                    ErrMsg = string.Format("{0}  contrast ECP fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readECP);
                            ErrMsg = string.Format("{0}  read ECP fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkECP);
                        ErrMsg = string.Format("{0}  check ECP fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeECP);
                    ErrMsg = string.Format("{0}  Write ECP fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.ECP.result = true;
            }

            //Playready抄写
            if (WritePlayready.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.Playready.data))
                {
                    ErrMsg = string.Format("Playready format error!\r\n{0}", keyInfo.Playready.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] PlayreadyData = SerialInit.HexToByte(keyInfo.Playready.data);
                Log.WriteInfoLog("Write Playready...");
                if (SerialCMD.SetFireTVPlayready(TVPort, PlayreadyData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writePlayready);
                    Log.WriteInfoLog("Check Playready...");
                    if (cfg_writecheck.PlayreadyCheckcheck ? SerialCMD.CheckFireTVPlayready(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkPlayready);
                        Log.WriteInfoLog("Read Playready...");
                        if (cfg_readcheck.PlayreadyReadcheck ? SerialCMD.ReadFireTVPlayready(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.PlayreadyReadcheck)
                            {
                                if (CommonMethod.CompareMD5(PlayreadyData, data))
                                {
                                    SetsuccessStatus(m_readPlayready);
                                }
                                else
                                {
                                    if (SerialInit.BytesCompare_Base64(data, PlayreadyData))
                                    {
                                        SetsuccessStatus(m_readPlayready);
                                    }
                                    else
                                    {
                                        SetfailStatus(m_readPlayready);
                                        ErrMsg = string.Format("{0}  contrast Playready fail!", SN);
                                        Log.WriteErrorLog(ErrMsg);
                                        goto end;
                                    }
                                }
                            }

                        }
                        else
                        {
                            SetfailStatus(m_readPlayready);
                            ErrMsg = string.Format("{0}  read Playready fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkPlayready);
                        ErrMsg = string.Format("{0}  check Playready fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writePlayready);
                    ErrMsg = string.Format("{0}  Write Playready fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.Playready.result = true;
            }

            #region FVP激活-放在Hash key抄写之后，应用于所有FireTV项目-已通过郁沛确认;
            if (WriteFVP.Checked)
            {
                Log.WriteInfoLog("Activate FVP...");
                byte[] FVPData = new byte[] { };
                if (SerialCMD.ActiveMiFireTVFVP(TVPort, FVPData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeFVP);
                    Log.WriteInfoLog("Check FVP...");
                    if (cfg_writecheck.FVPCheckcheck ? SerialCMD.CheckMiFireTVFVP(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkFVP);
                    }
                    else
                    {
                        SetfailStatus(m_checkFVP);
                        ErrMsg = string.Format("{0} check FVP fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeFVP);
                    ErrMsg = string.Format("Activate FVP Failed {0}", error);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                // fvp没key内容;
                //keyInfo.Hashkey.result = true;
            }
            #endregion

            // Dolby Key抄写;
            if ( cfg_writecheck.DolbyCheckcheck )
            {
                Log.WriteInfoLog("Check Dolby Key...");
                if ( !SerialCMD.CheckDolbyKey(TVPort, out result, out data, out error, SerailDelay) )
                {
                    ErrMsg = string.Format("{0} check Dolby fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            //Hash抄写
            if (WriteHash.Checked)
            {
                if (!CommonMethod.IsNumberAndWord(keyInfo.Hashkey.data))
                {
                    ErrMsg = string.Format("Hash format error!\r\n{0}", keyInfo.Hashkey.data);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                byte[] HashData = SerialInit.HexToByte(keyInfo.Hashkey.data);
                Log.WriteInfoLog("Write Hash...");
                if (SerialCMD.SetFireTVHashkey(TVPort, HashData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeHash);
                    Log.WriteInfoLog("Check Hash...");
                    if (cfg_writecheck.HashCheckcheck ? SerialCMD.CheckFireTVHashkey(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkHash);
                        Log.WriteInfoLog("Read Hash...");
                        if (cfg_readcheck.HashReadcheck ? SerialCMD.ReadFireTVHashkey(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.HashReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, HashData))
                                {
                                    SetsuccessStatus(m_readHash);
                                }
                                else
                                {
                                    SetfailStatus(m_readHash);
                                    ErrMsg = string.Format("{0}  contrast Hash fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readHash);
                            ErrMsg = string.Format("{0}  read Hash fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkHash);
                        ErrMsg = string.Format("{0}  check Hash fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeHash);
                    ErrMsg = string.Format("{0}  Write Hash fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.Hashkey.result = true;
            }

            //频道预置
            if (FunctionSettingNow.WriteChannel)
            {
                Log.WriteInfoLog("setting channel...");
                if (SerialCMD.SetChannel(TVPort, FunctionSettingNow.ChannelCode, out result, out data, out error, SerailDelay))
                {
                    /*
                    Log.WriteInfoLog("getting channel...");
                    if (SerialCMD.GetChannel(TVPort, out result, out data, out error))
                    {
                        if(SerialInit.BytesCompare_Base64(data, FunctionSettingNow.ChannelCode))
                        {

                        }
                        else
                        {
                            Log.WriteErrorLog(SN + "  get different channel");
                            goto end;
                        }
                    }
                    else
                    {
                        Log.WriteErrorLog(SN + "  fail to get channel");
                        goto end;
                    }*/
                    Log.WriteInfoLog(SN + "  set channel success");
                    SetcolorStatus(ChannelText, Color.FromArgb(128, 255, 128));
                }
                else
                {
                    ErrMsg = string.Format("{0}  fail to set channel!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            //OSD语言设置
            if (FunctionSettingNow.WriteOSD)
            {
                Log.WriteInfoLog("setting OSD language...");
                if (SerialCMD.SetOSDLanguage(TVPort, FunctionSettingNow.OSDLCode, out result, out data, out error, SerailDelay))
                {
                    if (cfg_readcheck.OSDReadcheck)
                    {
                        Log.WriteInfoLog("getting OSD language...");
                        if (SerialCMD.GetOSDLanguage(TVPort, out result, out data, out error, SerailDelay))
                        {
                            if (SerialInit.BytesCompare_Base64(data, FunctionSettingNow.OSDLCode))
                            {
                                SetcolorStatus(OSDText, Color.FromArgb(128, 255, 128));
                            }
                            else
                            {
                                ErrMsg = string.Format("{0}  get different OSD language!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            ErrMsg = string.Format("{0}  fail to get OSD language!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                        Log.WriteInfoLog("skip read OSD language...");
                }
                else
                {
                    ErrMsg = string.Format("{0}  fail to set OSD language!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            //Shop语言设置
            if (FunctionSettingNow.WriteSHOP)
            {
                Log.WriteInfoLog("setting SHOP language...");
                if (SerialCMD.SetShopLanguage(TVPort, FunctionSettingNow.ShopLCode, out result, out data, out error, SerailDelay))
                {
                    if (cfg_readcheck.SHOPReadcheck)
                    {
                        Log.WriteInfoLog("getting SHOP language...");
                        if (SerialCMD.GetShopLanguage(TVPort, out result, out data, out error, SerailDelay))
                        {
                            if (SerialInit.BytesCompare_Base64(data, FunctionSettingNow.ShopLCode))
                            {
                                SetcolorStatus(SHOPText, Color.FromArgb(128, 255, 128));
                            }
                            else
                            {
                                ErrMsg = string.Format("{0}  get different SHOP language!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            ErrMsg = string.Format("{0}  fail to get SHOP language!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                        Log.WriteInfoLog("skip read SHOP language...");
                }
                else
                {
                    ErrMsg = string.Format("{0}  fail to set SHOP language!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            // EDID Pid抄写;
            if (WriteEDIDPID.Checked)
            {
                // 4字节转成整数：0~65535,0x0000~0xffff;
                if (Regex.IsMatch(keyInfo.EDIDPid.data, "^[A-Fa-f0-9]{4}$"))
                {
                    byte[] EDIDPidData = SerialInit.strToToHexByte(keyInfo.EDIDPid.data);
                    Log.WriteInfoLog("Write EDID Pid...");
                    if (SerialCMD.SetEDIDPid(TVPort, EDIDPidData, out result, out data, out error, SerailDelay))
                    {
                        SetsuccessStatus(m_writeEDIDPID);
                        Log.WriteInfoLog("Read EDID Pid...");
                        if (cfg_readcheck.EDIDPIDReadcheck ? SerialCMD.ReadEDIDPid(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.EDIDPIDReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, EDIDPidData))
                                {
                                    SetsuccessStatus(m_readEDIDPID);
                                }
                                else
                                {
                                    SetfailStatus(m_readEDIDPID);
                                    ErrMsg = string.Format("{0}  contrast EDID PID fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readEDIDPID);
                            ErrMsg = string.Format("{0}  read EDID PID fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_writeEDIDPID);
                        ErrMsg = string.Format("{0}  Write EDID PID fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeEDIDPID);
                    ErrMsg = string.Format("{0}  The EDID PID Format Error!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.EDIDPid.result = true;
            }

            // EDID Mode Name抄写;
            if (WriteEDIDName.Checked)
            {
                // 首字符：只能数字和字母;
                if (Regex.IsMatch(keyInfo.EDIDModelName.data, "^[A-Za-z0-9]{1}[A-Za-z0-9_ \\.\\-]{2,12}[A-Za-z0-9]{1}$"))
                {
                    // 长度为13字节;
                    byte[] EDIDNameData = Encoding.ASCII.GetBytes(keyInfo.EDIDModelName.data);
                    Log.WriteInfoLog("Write EDID Mode Name...");
                    if (SerialCMD.SetEDIDModelName(TVPort, EDIDNameData, out result, out data, out error, SerailDelay))
                    {
                        SetsuccessStatus(m_writeEDIDName);
                        Log.WriteInfoLog("Read EDID Mode Name...");
                        if (cfg_readcheck.EDIDModeNameReadcheck ? SerialCMD.ReadEDIDModelName(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.EDIDModeNameReadcheck)
                            {
                                if (SerialInit.BytesCompare_Base64(data, EDIDNameData))
                                {
                                    SetsuccessStatus(m_readEDIDName);
                                }
                                else
                                {
                                    SetfailStatus(m_readEDIDName);
                                    ErrMsg = string.Format("{0}  contrast EDID Mode Name fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readEDIDName);
                            ErrMsg = string.Format("{0}  read EDID Mode Name fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_writeEDIDName);
                        ErrMsg = string.Format("{0}  Write EDID Mode Name fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeEDIDName);
                    ErrMsg = string.Format("{0}  The EDID Model Name Format Error!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.EDIDModelName.result = true;
            }

            // ACAS Key抄写;
            if (WriteACASKey.Checked)
            {
                // 1.acas key抄写前,必须先抄写playreadkey;
                // 2.将tool先抄写再抄写data;
                Log.WriteInfoLog("Write ACAC Key...");
                byte[] ACASKeyData = SerialInit.HexToByte(keyInfo.ACASKey_Data.data);
                if (SerialCMD.SetACASKeyData(TVPort, ACASKeyData, out result, out data, out error, SerailDelay))
                {
                    SetsuccessStatus(m_writeACASKey);
                    Log.WriteInfoLog("Check ACAS Key Data...");
                    if (cfg_writecheck.ACASKeyCheckcheck ? SerialCMD.CheckACASKeyData(TVPort, out result, out data, out error, SerailDelay) : true)
                    {
                        SetsuccessStatus(m_checkACASKey);
                        Log.WriteInfoLog("Read ACAS Key Data...");
                        if (cfg_readcheck.ACASKeyReadcheck ? SerialCMD.ReadACASKeyData(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            if (cfg_readcheck.ACASKeyReadcheck)
                            {
                                if (CommonMethod.CompareMD5(ACASKeyData, data))
                                {
                                    SetsuccessStatus(m_readACASKey);
                                }
                                else
                                {
                                    SetfailStatus(m_readACASKey);
                                    ErrMsg = string.Format("{0}  contrast ACAS Key Data fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                        }
                        else
                        {
                            SetfailStatus(m_readACASKey);
                            ErrMsg = string.Format("{0}  read ACAS Key Data fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_checkACASKey);
                        ErrMsg = string.Format("{0}  Check ACAS Key Data fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    SetfailStatus(m_writeACASKey);
                    ErrMsg = string.Format("{0}  Write ACAS Key Data fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                keyInfo.ACASKey_Data.result = true;
            }

            //Project ID 抄写检查
            if (ProjectIDNote.Text != LResource.SkipCovering)
            {
                Log.WriteInfoLog("Write projectID...");
                if (ProjectIDNote.Text == LResource.Covering || ProjectIDNote.Text == LResource.SkipReadCheck)
                {
                    SetspecificText(ProjectIDNote, ProjectIDNote.Text, Color.FromArgb(128, 255, 128));
                    byte[] param = CommonMethod.InttoBytelist(Convert.ToInt32(ProjectIDText.Text));
                    Log.WriteInfoLog("Set projectID...");
                    if (SerialCMD.SetProjectId(TVPort, param, out result, out data, out error, SerailDelay))
                    {
                        if (ProjectIDNote.Text != LResource.SkipReadCheck)
                        {
                            Log.WriteInfoLog("Check projectID...");
                            if (cfg_writedone.PIDWriteDelay > 0)
                            {
                                Thread.Sleep(cfg_writedone.PIDWriteDelay);//MS6586切完PID需要强制等待3s
                            }
                            if (SerialCMD.GetProjectID(TVPort, out result, out data, out error, SerailDelay, CommonMethod.IsEDIDCopy(midListNow)))
                            {
                                int readpid2 = CommonMethod.BytelisttoInt(data);
                                if (readpid2.ToString() != ProjectIDText.Text)
                                {
                                    SetcolorStatus(ProjectIDText, Color.Red);
                                    ErrMsg = SN + "  read project id:" + readpid2.ToString() + "different from written: " + ProjectIDText.Text + " error";
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                                else
                                {
                                    SetcolorStatus(ProjectIDText, Color.Green);
                                }
                            }
                            else
                            {
                                SetcolorStatus(ProjectIDText, Color.Red);
                                ErrMsg = string.Format("{0}  get project id error!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            Log.WriteInfoLog("Skip check projectID...");
                        }
                    }
                    else
                    {
                        SetcolorStatus(ProjectIDText, Color.Red);
                        ErrMsg = string.Format("{0}  set project id error!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    if (SerialCMD.GetProjectID(TVPort, out result, out data, out error, SerailDelay, CommonMethod.IsEDIDCopy(midListNow)))
                    {
                        int readpid = CommonMethod.BytelisttoInt(data);
                        if (readpid.ToString() != ProjectIDText.Text)
                        {
                            MessageBoxButtons messButton = MessageBoxButtons.YesNoCancel;
                            DialogResult dr = MessageBox.Show(LResource.MainboardPID + readpid.ToString() + LResource.DifferentFromSetting + "\r\n" + LResource.CoveringPID, LResource.Error, messButton);
                            if (dr == DialogResult.Yes)
                            {
                                SetspecificText(ProjectIDNote, LResource.Covering, Color.FromArgb(128, 255, 128));
                                byte[] param = CommonMethod.InttoBytelist(Convert.ToInt32(ProjectIDText.Text));
                                if (SerialCMD.SetProjectId(TVPort, param, out result, out data, out error, SerailDelay))
                                {
                                    if (cfg_writedone.PIDWriteDelay > 0)
                                    {
                                        Thread.Sleep(cfg_writedone.PIDWriteDelay);//MS6586切完PID需要强制等待3s
                                    }
                                    Log.WriteInfoLog("Check projectID...");
                                    if (SerialCMD.GetProjectID(TVPort, out result, out data, out error, SerailDelay, CommonMethod.IsEDIDCopy(midListNow)))
                                    {
                                        int readpid2 = CommonMethod.BytelisttoInt(data);
                                        if (readpid2.ToString() != ProjectIDText.Text)
                                        {
                                            SetcolorStatus(ProjectIDText, Color.Red);
                                            ErrMsg = SN + "  read project id:" + readpid2.ToString() + "different from written: " + ProjectIDText.Text + " error";
                                            Log.WriteErrorLog(ErrMsg);
                                            goto end;
                                        }
                                        else
                                        {
                                            SetcolorStatus(ProjectIDText, Color.Green);
                                        }
                                    }
                                    else
                                    {
                                        SetcolorStatus(ProjectIDText, Color.Red);
                                        ErrMsg = string.Format("{0}  get project id error!", SN);
                                        Log.WriteErrorLog(ErrMsg);
                                        goto end;
                                    }
                                }
                                else
                                {
                                    SetcolorStatus(ProjectIDText, Color.Red);
                                    ErrMsg = string.Format("{0}  set project id error!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                            else if (dr == DialogResult.No)
                            {
                                SetspecificText(ProjectIDNote, LResource.SkipCovering, Color.Yellow);
                                SetcolorStatus(ProjectIDText, Color.Yellow);
                            }
                            else
                            {
                                SetspecificText(ProjectIDNote, readpid.ToString(), Color.Red);
                                SetcolorStatus(ProjectIDText, Color.Red);
                                goto end;
                            }
                        }
                        else
                        {
                            SetcolorStatus(ProjectIDText, Color.FromArgb(128, 255, 128));
                        }
                    }
                    else
                    {
                        ErrMsg = string.Format("{0}  Read ProjectID fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
            }

            //检查ClientType
            if (ClientTypeNote.Text != LResource.SkipChecking)
            {
                Log.WriteInfoLog("Read ClientType...");
                if (SerialCMD.GetClientType(TVPort, out result, out data, out error, SerailDelay))
                {
                    string ctype = Encoding.ASCII.GetString(data);
                    if (ctype != ClientTypeText.Text)
                    {
                        MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                        DialogResult dr = MessageBox.Show(LResource.MainboardCType + ctype + LResource.differentfromserver + ClientTypeText.Text + "\r\n" + LResource.SkipCTypeChecking, LResource.Error, messButton);
                        if (dr == DialogResult.OK)
                        {
                            SetspecificText(ClientTypeNote, LResource.SkipChecking, Color.Yellow);
                            SetcolorStatus(ClientTypeText, Color.Yellow);
                        }
                        else
                        {
                            SetspecificText(ClientTypeNote, ctype, Color.Red);
                            SetcolorStatus(ClientTypeText, Color.Red);
                            goto end;
                        }
                    }
                    else
                    {
                        SetcolorStatus(ClientTypeText, Color.FromArgb(128, 255, 128));
                    }
                }
                else
                {
                    ErrMsg = string.Format("{0}  Read ClientType fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            //白平衡初始化
            if (FunctionSettingNow.WBInit)
            {
                Log.WriteInfoLog("WhiteBalance init...");
                if (SerialCMD.WBInit(TVPort, out result, out data, out error, SerailDelay))
                {

                }
                else
                {
                    ErrMsg = string.Format("{0}  WhiteBalance ini fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            //白平衡赋值
            if (FunctionSettingNow.WriteWB)
            {
                Log.WriteInfoLog("Set normal RGB...");
                if (SerialCMD.SetWBNormal(TVPort, FunctionSettingNow.NormalRGB, out result, out data, out error, SerailDelay))
                {
                    Log.WriteInfoLog("Set cool RGB...");
                    if (SerialCMD.SetWBCool(TVPort, FunctionSettingNow.CoolRGB, out result, out data, out error, SerailDelay))
                    {
                        Log.WriteInfoLog("Set warm RGB...");
                        if (SerialCMD.SetWBWarm(TVPort, FunctionSettingNow.WarmRGB, out result, out data, out error, SerailDelay))
                        {
                            SetcolorStatus(WBPathText, Color.FromArgb(128, 255, 128));
                        }
                        else
                        {
                            ErrMsg = string.Format("{0}  Set warm RGB fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        ErrMsg = string.Format("{0}  Set cool RGB fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    ErrMsg = string.Format("{0}  Set normal RGB fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            //Roku客户服务信息抄写
            if (midListNow.rokuCustomer != null)
            {
                string brand = midListNow.rokuCustomer.brand;
                Log.WriteInfoLog("Write Roku brand...");
                if (SerialCMD.SetROKUBrand(TVPort, Encoding.ASCII.GetBytes(brand), out result, out data, out error, SerailDelay))
                {
                    Log.WriteInfoLog("Check Roku brand...");
                    if (SerialCMD.CheckROKUBrand(TVPort, out result, out data, out error, SerailDelay))
                    {
                        Log.WriteInfoLog("Read Roku brand...");
                        if (SerialCMD.GetROKUBrand(TVPort, out result, out data, out error, SerailDelay))
                        {
                            if (SerialInit.BytesCompare_Base64(data, Encoding.ASCII.GetBytes(brand)))
                            {
                                Log.WriteInfoLog("ROKU brand 写入成功:" + Encoding.ASCII.GetString(data));
                            }
                            else
                            {
                                ErrMsg = string.Format("{0}  Contrast ROKU brand fail!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            ErrMsg = string.Format("{0}  Read ROKU brand fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        ErrMsg = string.Format("{0}  Check ROKU brand fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    ErrMsg = string.Format("{0}  Write ROKU brand fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                string model = midListNow.rokuCustomer.oemmodel;
                Log.WriteInfoLog("Write Roku model...");
                if (SerialCMD.SetModelName(TVPort, Encoding.ASCII.GetBytes(model), out result, out data, out error, SerailDelay))
                {
                    Log.WriteInfoLog("Check Roku model...");
                    if (SerialCMD.CheckModelName(TVPort, out result, out data, out error, SerailDelay))
                    {
                        Log.WriteInfoLog("Read Roku model...");
                        if (SerialCMD.GetModelName(TVPort, out result, out data, out error, SerailDelay))
                        {
                            if (SerialInit.BytesCompare_Base64(data, Encoding.ASCII.GetBytes(model)))
                            {
                                Log.WriteInfoLog("ROKU model 写入成功:" + Encoding.ASCII.GetString(data));
                            }
                            else
                            {
                                ErrMsg = string.Format("{0}  Contrast ROKU model fail!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            ErrMsg = string.Format("{0}  Read ROKU model fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        ErrMsg = string.Format("{0}  Check ROKU model fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    ErrMsg = string.Format("{0}  Write ROKU model fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                string[] dateInit = midListNow.rokuCustomer.productiondate.Split('-');
                byte[] productdate = new byte[3] { Convert.ToByte(dateInit[0]), Convert.ToByte(dateInit[1]), Convert.ToByte(dateInit[2]) };
                Log.WriteInfoLog("Write Roku production date...");
                if (SerialCMD.SetROKUProductionDate(TVPort, productdate, out result, out data, out error, SerailDelay))
                {
                    Log.WriteInfoLog("Check Roku production date...");
                    if (SerialCMD.CheckROKUProductionDate(TVPort, out result, out data, out error, SerailDelay))
                    {
                        Log.WriteInfoLog("Read Roku production date...");
                        if (SerialCMD.GetROKUProductionDate(TVPort, out result, out data, out error, SerailDelay))
                        {
                            string date = "20" + productdate[0].ToString() + "." + productdate[1].ToString() + ".WW" + productdate[2].ToString();
                            if (Encoding.ASCII.GetString(data) == date)
                            {
                                Log.WriteInfoLog("ROKU production date 写入成功:" + Encoding.ASCII.GetString(data));
                            }
                            else
                            {
                                ErrMsg = string.Format("{0}  Contrast ROKU production fail!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            ErrMsg = string.Format("{0}  Read ROKU production fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        ErrMsg = string.Format("{0}  Check ROKU production fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    ErrMsg = string.Format("{0}  Write ROKU production fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                string region = midListNow.rokuCustomer.region;
                Log.WriteInfoLog("Write Roku region...");
                if (SerialCMD.SetROKURegion(TVPort, Encoding.ASCII.GetBytes(region), out result, out data, out error, SerailDelay))
                {
                    Log.WriteInfoLog("Check Roku region...");
                    if (SerialCMD.CheckROKURegion(TVPort, out result, out data, out error, SerailDelay))
                    {
                        Log.WriteInfoLog("Read Roku region...");
                        if (SerialCMD.GetROKURegion(TVPort, out result, out data, out error, SerailDelay))
                        {
                            if (SerialInit.BytesCompare_Base64(data, Encoding.ASCII.GetBytes(region)))
                            {
                                Log.WriteInfoLog("ROKU region 写入成功:" + Encoding.ASCII.GetString(data));
                            }
                            else
                            {
                                ErrMsg = string.Format("{0}  Contrast ROKU region fail!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            ErrMsg = string.Format("{0}  Read ROKU region fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        ErrMsg = string.Format("{0}  Check ROKU region fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    ErrMsg = string.Format("{0}  Write ROKU region fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                string phone = midListNow.rokuCustomer.supportphone;
                Log.WriteInfoLog("Write Roku phone...");
                if (SerialCMD.SetROKUSupportPhone(TVPort, Encoding.ASCII.GetBytes(phone), out result, out data, out error, SerailDelay))
                {
                    Log.WriteInfoLog("Check Roku phone...");
                    if (SerialCMD.CheckROKUSupportPhone(TVPort, out result, out data, out error, SerailDelay))
                    {
                        Log.WriteInfoLog("Read Roku phone...");
                        if (SerialCMD.GetROKUSupportPhone(TVPort, out result, out data, out error, SerailDelay))
                        {
                            if (SerialInit.BytesCompare_Base64(data, Encoding.ASCII.GetBytes(phone)))
                            {
                                Log.WriteInfoLog("ROKU phone 写入成功:" + Encoding.ASCII.GetString(data));
                            }
                            else
                            {
                                ErrMsg = string.Format("{0}  Contrast ROKU phone fail!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            ErrMsg = string.Format("{0}  Read ROKU phone fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        ErrMsg = string.Format("{0}  Check ROKU phone fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    ErrMsg = string.Format("{0}  Write ROKU phone fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                string url = midListNow.rokuCustomer.supporturl;
                Log.WriteInfoLog("Write Roku url...");
                if (SerialCMD.SetROKUSupportURL(TVPort, Encoding.ASCII.GetBytes(url), out result, out data, out error, SerailDelay))
                {
                    Log.WriteInfoLog("Check Roku url...");
                    if (SerialCMD.CheckROKUSupportURL(TVPort, out result, out data, out error, SerailDelay))
                    {
                        Log.WriteInfoLog("Read Roku url...");
                        if (SerialCMD.GetROKUSupportURL(TVPort, out result, out data, out error, SerailDelay))
                        {
                            if (SerialInit.BytesCompare_Base64(data, Encoding.ASCII.GetBytes(url)))
                            {
                                Log.WriteInfoLog("ROKU url 写入成功:" + Encoding.ASCII.GetString(data));
                            }
                            else
                            {
                                ErrMsg = string.Format("{0}  Contrast ROKU url fail!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            ErrMsg = string.Format("{0}  Read ROKU url fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        ErrMsg = string.Format("{0}  Check ROKU url fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    ErrMsg = string.Format("{0}  Write ROKU url fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                if (midListNow.rokuCustomer.remotetype.Length > 0 && midListNow.rokuCustomer.remotetype != "null")
                {
                    byte[] remotetype = new byte[1] { Convert.ToByte(midListNow.rokuCustomer.remotetype) };
                    Log.WriteInfoLog("Write Roku remotetype...");
                    if (SerialCMD.SetROKURemoteType(TVPort, remotetype, out result, out data, out error, SerailDelay))
                    {
                        Log.WriteInfoLog("Check Roku remotetype...");
                        if (SerialCMD.CheckROKURemoteType(TVPort, out result, out data, out error, SerailDelay))
                        {
                            Log.WriteInfoLog("Read Roku remotetype...");
                            if (SerialCMD.GetROKURemoteType(TVPort, out result, out data, out error, SerailDelay))
                            {
                                if (SerialInit.BytesCompare_Base64(data, remotetype))
                                {
                                    Log.WriteInfoLog("ROKU remotetype 写入成功:" + Encoding.ASCII.GetString(data));
                                }
                                else
                                {
                                    ErrMsg = string.Format("{0}  Contrast ROKU remotetype fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                            else
                            {
                                ErrMsg = string.Format("{0}  Read ROKU remotetype fail!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            ErrMsg = string.Format("{0}  Check ROKU remotetype fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        ErrMsg = string.Format("{0}  Write ROKU remotetype fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                SetcolorStatus(ProductMsg_Text, Color.FromArgb(128, 255, 128));
            }

            // DSN抄写;
            if (WriteDSN.Checked)
            {
                if (FunctionSettingNow.MITVEnable)
                {// 小米的DSN抄写不用这么多处理;
                    if (!CommonMethod.IsNumberAndWord(keyInfo.DSN.data))
                    {
                        ErrMsg = string.Format("DSN format error!\r\n{0}", keyInfo.DSN.data);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                    byte[] DSNData = System.Text.Encoding.ASCII.GetBytes(keyInfo.DSN.data);
                    Log.WriteInfoLog("Write DSN...");
                    if (SerialCMD.SetFireTVDSN(TVPort, DSNData, out result, out data, out error, SerailDelay))
                    {
                        SetsuccessStatus(m_writeDSN);
                        Log.WriteInfoLog("Check DSN...");
                        if (cfg_writecheck.DSNCheckcheck ? SerialCMD.CheckFireTVDSN(TVPort, out result, out data, out error, SerailDelay) : true)
                        {
                            SetsuccessStatus(m_checkDSN);
                            Log.WriteInfoLog("Read DSN...");
                            if (cfg_readcheck.DSNReadcheck ? SerialCMD.GetFireTVDSN(TVPort, out result, out data, out error, SerailDelay) : true)
                            {
                                if (SerialInit.BytesCompare_Base64(data, DSNData))
                                {
                                    SetsuccessStatus(m_readDSN);
                                    //DSN读取别对成功
                                }
                                else
                                {
                                    SetfailStatus(m_readDSN);
                                    ErrMsg = string.Format("{0}  contrast DSN fail!", SN);
                                    Log.WriteErrorLog(ErrMsg);
                                    goto end;
                                }
                            }
                            else
                            {
                                SetfailStatus(m_readDSN);
                                ErrMsg = string.Format("{0}  read DSN fail!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                        else
                        {
                            SetfailStatus(m_checkDSN);
                            ErrMsg = string.Format("{0}  check DSN fail!", SN);
                            Log.WriteErrorLog(ErrMsg);
                            goto end;
                        }
                    }
                    else
                    {
                        SetfailStatus(m_writeDSN);
                        ErrMsg = string.Format("{0}  Write DSN fail!", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {// 如果是G客户，要在抄写其他key前时行fsn+psn查重处理;
                    // 计算函数耗时;
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    if (SN == null)
                    {
                        MessageBox.Show("Please scan to trigger testing");
                        goto end;
                    }
                    if (SN.Trim().Length == 0)
                    {
                        SetsuccessStatus(m_writeDSN);
                        Log.WriteInfoLog("Check DSN...");
                        if (cfg_writecheck.DSNCheckcheck)
                        {
                            if (SerialCMD.CheckFireTVDSN(TVPort, out result, out data, out error, SerailDelay))
                            {
                                SetsuccessStatus(m_checkDSN);
                                Log.WriteInfoLog("Read DSN...");
                                if (cfg_readcheck.DSNReadcheck)
                                {
                                    if (SerialCMD.GetFireTVDSN(TVPort, out result, out data, out error, SerailDelay))
                                    {
                                        if (SerialInit.BytesCompare_Base64(data, DSNData))
                                        {
                                            SetsuccessStatus(m_readDSN);
                                            //DSN读取别对成功
                                        }
                                        else
                                        {
                                            SetfailStatus(m_readDSN);
                                            ErrMsg = string.Format("{0}  contrast DSN fail!", SN);
                                            Log.WriteErrorLog(ErrMsg);
                                            goto end;
                                        }
                                    }
                                    else
                                    {
                                        SetfailStatus(m_readDSN);
                                        ErrMsg = string.Format("{0}  read DSN fail!", SN);
                                        Log.WriteErrorLog(ErrMsg);
                                        goto end;
                                    }
                                }
                            }
                            else
                            {
                                SetfailStatus(m_checkDSN);
                                ErrMsg = string.Format("{0}  check DSN fail!", SN);
                                Log.WriteErrorLog(ErrMsg);
                                goto end;
                            }
                        }
                    }
                    else
                    {
                        ErrMsg = string.Format("{0}     Get Device Code Error", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }

                    watch.Stop();
                    Log.WriteInfoLog(string.Format("Write DSN Elapsed={0}", watch.Elapsed.TotalMilliseconds));
                }

                keyInfo.DSN.result = true;
            }

            #region 小米FireTV功能;
            if (FunctionSettingNow.MITVEnable)
            {
#if true
                // 读取PSN;
                byte[] result_psn;
                byte[] data_psn;
                if (SerialCMD.ReadFireTVPSN(TVPort, out result_psn, out data_psn, out error, SerailDelay))
                {
                    _MiKey._PSN = Encoding.ASCII.GetString(data_psn);
                }
                else
                {
                    ErrMsg = string.Format("读取PSN失败 {0}", error);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
#else
                //小米 2717版不可读 PSN的24K需要生产，更新一版不读取PSN功能的抄写软件
                _MiKey._PSN = DateTime.Now.ToString("yyyy-MM-dd-HH-mm:ss");
#endif

                // CVT抄写: Hashkey、HDCP_KEY1.4、HDCP2.2_KEY、CI_PLUS_KEY、ECP_KEY、FVP
                if (cfg_writecheck.HashCheckcheck ? !SerialCMD.CheckFireTVHashkey(TVPort, out result, out data, out error, SerailDelay) : false)
                {
                    ErrMsg = string.Format("Check Hashkey失败 {0}", error);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                if (cfg_writecheck.CI_plusCheckcheck ? !SerialCMD.CheckCikey(TVPort, out result, out data, out error, SerailDelay) : false)
                {
                    ErrMsg = string.Format("Check Cikey失败 {0}", error);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                if (cfg_writecheck.ECPCheckcheck ? !SerialCMD.CheckECP(TVPort, out result, out data, out error, SerailDelay) : false)
                {
                    ErrMsg = string.Format("Check Cikey失败 {0}", error);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                if (cfg_writecheck.HDCPCheckcheck ? !SerialCMD.CheckHDCP(TVPort, out result, out data, out error, SerailDelay) : false)
                {
                    ErrMsg = string.Format("Check HDCP 失败 {0}", error);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                if (cfg_writecheck.HDCP22Checkcheck ? !SerialCMD.CheckHDCP22(TVPort, out result, out data, out error, SerailDelay) : false)
                {
                    ErrMsg = string.Format("Check HDCP22 失败 {0}", error);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }

                // 读取HDCP;
                if (cfg_readcheck.HDCPReadcheck)
                {
                    if (!SerialCMD.GetHDCPKey(TVPort, out result, out data, out error, SerailDelay))
                    {
                        ErrMsg = string.Format("读取HDCP失败 {0}", error);
                        Log.WriteErrorLog(ErrMsg);
                        _MiKey._HDCP14 = 0;
                        goto end;
                    }
                    else
                    {
                        _MiKey._HDCP14 = data.Length;
                    }
                }

                // 读取HDCP;
                if (cfg_readcheck.HDCP22Readcheck)
                {
                    if (!SerialCMD.GetHDCPKey22(TVPort, out result, out data, out error, SerailDelay))
                    { 
                        ErrMsg = string.Format("读取HDCP22失败 {0}", error);
                        Log.WriteErrorLog(ErrMsg);
                        _MiKey._HDCP22 = 0;
                        goto end;
                    }
                    else
                    {
                        _MiKey._HDCP22 = data.Length;
                    }
                }                
            }
#endregion

            // 生成IDM报文;
            keycontent = GenerateReportInfo();

            //自定义指令发送
            if (FunctionSettingNow.CustomCMD != null)
            {
                if (FunctionSettingNow.CustomCMD.Count > 0)
                {
                    foreach (string cmd in FunctionSettingNow.CustomCMD.Values)
                    {
                        byte[] Cmddata = SerialInit.HexToByte(cmd);
                        TVPort.Write(Cmddata, 0, Cmddata.Count());
                        Thread.Sleep(500);
                    }
                }
            }

#region 波兰工厂DHA功能-抄写所有Key后执行Trigger和Check指令；
            if (FunctionSettingNow.DHA == true)
            {
                Log.WriteInfoLog("Start to Trigger DHA...");
                if (SerialCMD.TriggerDHA(TVPort, out result, out data, out error, SerailDelay))
                {
                    Thread.Sleep(FunctionSettingNow.CheckDHAWaitTime);
                    Log.WriteInfoLog("Start to Check DHA...");
                    if (!SerialCMD.CheckDHA(TVPort, out result, out data, out error, SerailDelay))
                    {
                        ErrMsg = string.Format("{0} Check DHA Fail", SN);
                        Log.WriteErrorLog(ErrMsg);
                        goto end;
                    }
                }
                else
                {
                    ErrMsg = string.Format("{0} Trigger DHA Fail", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }
            #endregion
            #endregion

            //数据上传
            if (midListNow.host == "LocalPC" && !preloadNow)
            {// 离线抄写
                if (GetLocalKeyCount.DeleteLocalKeys(keypath, keyStream, keyReader))
                {
                    TestResult = 1;
                    UploadCopyCount();
                    LocalTxtRecord.LocalRecord(keycontent + "sversionid=" + localmidList.version + "&clienttype=" + localmidList.clienttype + "&ordernum=" + orderNow + "\r\n", orderNow);
                }
                else
                {
                    ErrMsg = "Fail to delete local keys";
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }
            else if (preloadNow)
            {// 预绑定抄写;
                //更新DB抄写状态
                if (SQLiteHelper.UpdateCopyStatus(localDBNow, SN, out string copydate))
                {
                    UploadCopyCount();
                    TestResult = 1;
                }
                else
                {
                    ErrMsg = string.Format("{0}  update copy record fail!", SN);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
                //上传抄写状态
                if (midListNow.host != "LocalPC")
                    //CommonMethod.UploadPreloadCopyResult(MidAddressNow.host, copydate, SN, localDBNow, errorDBNow, false, "", FunctionSettingNow.ReportTimeOut);
                    V2Method.ReportOfflineData(MidAddressNow.host, copydate, SN, localDBNow, errorDBNow, false, "");
            }
            else if (!CommonMethod.HTTPChecker(midListNow.host))
            {
                Log.WriteGetKeyLog("Order:" + orderNow + " host is null,scanning sn:" + SN);
                TestResult = 1;
                UploadCopyCount();
                UpdateKeys(midListNow.keytype, false);
            }
            else
            {// 在线抄写;
                if (WriteDID.Checked)
                {
                    //if (CommonMethod.UploadCopyResult(keycontent + "sversionid=" + midListNow.version + "&clienttype=" + midListNow.clienttype + "&ordernum=" + orderNow, midListNow.host, errorDBNow, orderNow, false, "", FunctionSettingNow.ReportTimeOut))
                    if (V2Method.ReportOnlineData(midListNow.host, orderNow, V2Method.GetReportJson(orderNow, SN, isNodid:false, ref keyInfo), errorDBNow,  false, "", FunctionSettingNow.ReportTimeOut))
                    {
                        TestResult = 1;
                    }
                    else
                    {
                        TestResult = 0;
                        UploadCopyCount();
                        ErrMsg = "上报结果到MID系统失败";
                        Log.WriteErrorLog(ErrMsg);
                        UpdateKeys(midListNow.keytype, false);
                        goto end;
                    }
                }
                else
                {
                    if (SN.Trim().Length > 0)
                    {
                        keycontent += "nodid=true&";
                        //if (CommonMethod.UploadCopyResult(keycontent + "sversionid=" + midListNow.version + "&clienttype=" + midListNow.clienttype + "&ordernum=" + orderNow, midListNow.host, errorDBNow, orderNow, false, "", FunctionSettingNow.ReportTimeOut))
                        if (V2Method.ReportOnlineData(midListNow.host, orderNow, V2Method.GetReportJson(orderNow, SN, isNodid: true, ref keyInfo), errorDBNow, false, "", FunctionSettingNow.ReportTimeOut))
                        {
                            TestResult = 1;
                        }
                        else
                        {
                            TestResult = 0;
                            UploadCopyCount();
                            ErrMsg = "上报结果到MID系统失败";
                            Log.WriteErrorLog(ErrMsg);
                            UpdateKeys(midListNow.keytype, false);
                            goto end;
                        }
                    }
                    else
                    {
                        LocalTxtRecord.LocalRecord(midListNow.host + "/report.do?\r\n" + keycontent + "sversionid=" + midListNow.version + "&clienttype=" + midListNow.clienttype + "&ordernum=" + orderNow + "\r\n\r\n", orderNow);
                        if (FunctionSettingNow.AllowNoScanning)
                        {
                            TestResult = 1;
                        }
                        else
                        {
                            ErrMsg = "未扫码启动数据抄写";
                            Log.WriteErrorLog(ErrMsg);
                            MessageBox.Show("You must scan to start the burning!");
                            TestResult = 0;
                        }
                    }
                }
                // 上报完成后,更新本地数据库Key的数量;
                UploadCopyCount();
                // 同时,在线更新Key数量;
                UpdateKeys(midListNow.keytype, false);
            }

            if (FunctionSettingNow.ExportSNACASID)
            {// 只有抄写成功,才输出ACASID;
                CommonMethod.ExportSNACASID(orderNow, SN, strACASID);

                if (!SanhuaMethod.UploadIdcData(SN, strACASID, out error))
                {
                    TestResult = 0;
                    ErrMsg = string.Format("{0}  UploadIdcData fail! {1}", SN, error);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }

            if (CommonMethod.GetLoginAccout().Equals("Sanhua", StringComparison.OrdinalIgnoreCase))
            {
                SerialCMD.ReadJapaneseACASID(TVPort, out result, out data, out error, SerailDelay);
                CommonMethod.ExportSNACASID(orderNow, SN, Encoding.ASCII.GetString(data));
            }

#region 小米FireTV功能;
            if (FunctionSettingNow.MITVEnable)
            {
                if (!ReportMIInfo(out error))
                {
                    TestResult = 0;
                    ErrMsg = string.Format("{0}  ReportMIInfo ini fail! {1}", SN, error);
                    Log.WriteErrorLog(ErrMsg);
                    goto end;
                }
            }
#endregion

            Thread.Sleep(FunctionSettingNow.Wait_after_completion);
            SetsuccessStatus(ResultStatus);
        end:
            // 退出工厂模式;
            if (FunctionSettingNow.LeaveFactory ? !SerialCMD.LeaveFactory(TVPort, out result, out data, out error, SerailDelay) : false )
            {
                ErrMsg = string.Format("LeaveFactory Fail\r\n {0}", SN);
                Log.WriteErrorLog(ErrMsg);
            }

#region 只有惠州工厂才启用G客户防呆措施;
            if (FunctionSettingNow.NTF)
            {
                string strLastResult = "";
                string strLastSN = CommonMethod.ReadProfileString("MOKAFactoryTools", "LastGSN", "");
                if (strLastSN.Equals(SN, StringComparison.OrdinalIgnoreCase))
                {
                    if (TestResult == 0)
                    {
                        int lastCount = 0;
                        // 更新连续测试中累计失败的次数
                        string strFailCount = CommonMethod.ReadProfileString("MOKAFactoryTools", "GFailCount", "0");
                        int.TryParse(strFailCount, out lastCount);
                        CommonMethod.WriteProfileString("MOKAFactoryTools", "GFailCount", (++lastCount).ToString());

                        if (lastCount >= 2)
                        {// 累计2次Fail;
                            ShowVerifyDelegate("累计2次测试失败，禁止再测试，请做好坏机标记");
                        }
                    }

                    // 获取上一次抄写状态;
                    strLastResult = CommonMethod.ReadProfileString("MOKAFactoryTools", "LastGResult", "");

                    // 更新抄写结果;
                    CommonMethod.WriteProfileString("MOKAFactoryTools", "LastGResult", TestResult != 0 ? "1" : "0");
                }
                else
                {
                    CommonMethod.WriteProfileString("MOKAFactoryTools", "LastGSN", SN);
                    // 重置连续测试中累计失败的次数为0;
                    CommonMethod.WriteProfileString("MOKAFactoryTools", "GFailCount", TestResult == 0 ? "1" : "0");
                    // 更新抄写状态;
                    CommonMethod.WriteProfileString("MOKAFactoryTools", "LastGResult", TestResult != 0 ? "1" : "0");

                    // 如果是试产NTF,且第一次测试就Fail,提示再测试多一次;
                    if (TestResult == 0 && nOrderType == 0)
                    {
                        Log.WriteErrorLog("试产订单：请再测试一次\r\n第一次测试为FAIL，请再测试确认结果！");
                        ShowVerifyDelegate("试产订单：请再测试一次\r\n第一次测试为FAIL，请再测试确认结果！");
                    }
                }

                if (strLastResult.ToString().Equals("0") && (TestResult == 1) && (nOrderType == 0))
                {
                    // 上次抄写是失败,这次是成功的,试产NTF要再次要求抄写一次才能上报AMTest.
                    ErrMsg = "试产订单：请再测试一次\r\n上一次测试为FAIL，需要连续2次PASS，请再测试确认结果！";
                    Log.WriteErrorLog(ErrMsg);
                    ShowVerifyDelegate(ErrMsg);
                    // 仍设置为失败;
                    TestResult = 2;
                }

                if (!ntfBLL.SetDataBuringResult(FunctionSettingNow.Line, FunctionSettingNow.Station, SN, keyInfo.DSN, TestResult == 0 ? false : true, strLastSN, nOrderType, TestResult == 0 ? ErrMsg : ""))
                {
                    //ntf失败,也需要提示;
                    ErrMsg = string.Format("统计NTF失败:{0}", SN);
                    Log.WriteErrorLog(ErrMsg);
                    TestResult = 0;
                }
                else
                {
                    if ((TestResult == 1) && ntfBLL.ResultType.Equals("NTF", StringComparison.OrdinalIgnoreCase))
                    {
                        // TestResut == 0 && TestResut == 2时，也不提示NTF;
                        ErrMsg = string.Format("结果类型为NTF，请将产品做好NTF标记:{0}", SN);
                        ShowVerifyDelegate(ErrMsg);
                    }
                }

                if (TestResult != 2)
                { // 上报抄写结果到MES系统中;
                    string strOutMsg;
                    string returnObject;
                    if (!GMethod.ReportDataBurningResultToMES(SN, keyInfo.DSN, (TestResult != 0) ? "Pass" : "Fail", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), errorDBNow, out strOutMsg, out returnObject))
                    {
                        ErrMsg = string.Format("上报抄写结果到MES失败，请紧急处理:{0}", strOutMsg);
                        Log.WriteErrorLog(ErrMsg);
                        // 上报MES失败,重置为False
                        TestResult = 0;
                    }

                    // 将测试结果保存到Kayla要求的csv文件中;
                    GMethod.GeneratKaylaData(FunctionSettingNow.Line, FunctionSettingNow.Station, OrderText.Text, SN, startTime, DateTime.Now, returnObject, keyInfo, TestResult != 0 ? true : false);
                }
            }
#endregion

            if (TestResult == 0)
            {
                if (ErrMsg == "")
                    ErrMsg = error;
                SetfailStatus(ResultStatus);
                if (midListNow.host == "LocalPC" && !preloadNow)
                {
                    GetLocalKeyCount.UnlockLocalKeys(keypath, keyStream, keyReader);
                }

                // 启动NG弹框功能;
                ShowVerifyDelegate(ErrMsg);
                Thread.Sleep(300);
            }

            if (midListNow.host == "LocalPC" && !preloadNow)
            {
                GetLocalKeysCount();
            }
        stop:
            timer1.Stop();
            usingTime = 0;
            EnableText(SNText);
            EnableButton(BtnClickstart);
            SN = "";
        }

        /// <summary>
        /// 显示白平衡配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBtnWBView(object sender, EventArgs e)
        {
            SNText.Focus();
            if (FunctionSettingNow.WriteWB)
            {
                MessageBox.Show("NormalR:" + FunctionSettingNow.NormalRGB[0] + "\r\nNormalG:" + FunctionSettingNow.NormalRGB[1] + "\r\nNormalB:" + FunctionSettingNow.NormalRGB[2] + "\r\nCoolR:" + FunctionSettingNow.CoolRGB[0] + "\r\nCoolG:" + FunctionSettingNow.CoolRGB[1] + "\r\nCoolB:" + FunctionSettingNow.CoolRGB[2] + "\r\nWarmR:" + FunctionSettingNow.WarmRGB[0] + "\r\nWarmG:" + FunctionSettingNow.WarmRGB[1] + "\r\nWarmB:" + FunctionSettingNow.WarmRGB[2]);
            }
            else
            {
                MessageBox.Show(LResource.WBNoSet);
            }
        }

        /// <summary>
        /// 更新key的状态
        /// </summary>
        /// <param name="keys">GetMIDInfo的keytype字典</param>
        /// <returns></returns>
        public bool UpdateKeys(Dictionary<string, string> keys, bool autokey)
        {
            GetOrderRemainKeyCount(orderNow);
            if (keys.ContainsKey("DeviceID"))
            {
                if (cfg_writedone.DIDWrite_YesNo)
                    SetCheckboxStatus(WriteDID, true);
                UpdateKeyCount("DeviceID", midListNow.clienttype, autokey);
            }
            if (keys.ContainsKey("MAC"))
            {
                if (cfg_writedone.MacWrite_YesNo)
                    SetCheckboxStatus(WriteMac, true);
                UpdateKeyCount("MAC", keys["MAC"], autokey);
            }
            if (keys.ContainsKey("HDCP_KEY"))
            {
                if (cfg_writedone.HDCPWrite_YesNo)
                    SetCheckboxStatus(WriteHDCP, true);
                UpdateKeyCount("HDCP_KEY", keys["HDCP_KEY"], autokey);
            }
            if (keys.ContainsKey("CI_PLUS_KEY"))
            {
                if (cfg_writedone.CI_plusWrite_YesNo)
                    SetCheckboxStatus(WriteCiplus, true);
                UpdateKeyCount("CI_PLUS_KEY", keys["CI_PLUS_KEY"], autokey);
            }
            if (keys.ContainsKey("Widevine_KEY"))
            {
                if (cfg_writedone.WidevineWrite_YesNo)
                    SetCheckboxStatus(WriteWidevine, true);
                UpdateKeyCount("Widevine_KEY", keys["Widevine_KEY"], autokey);
            }
            if (keys.ContainsKey("HDCP2.2_KEY"))
            {
                if (cfg_writedone.HDCP22Write_YesNo)
                    SetCheckboxStatus(WriteHDCP22, true);
                UpdateKeyCount("HDCP2.2_KEY", keys["HDCP2.2_KEY"], autokey);
            }
            if (keys.ContainsKey("NETFILX_ESN"))
            {
                if (cfg_writedone.ESNWrite_YesNo)
                    SetCheckboxStatus(WriteESN, true);
                UpdateKeyCount("NETFILX_ESN", keys["NETFILX_ESN"], autokey);
            }
            if (keys.ContainsKey("Attestation_key"))
            {
                if (cfg_writedone.AttestationWrite_YesNo)
                    SetCheckboxStatus(WriteAttestation, true);
                UpdateKeyCount("Attestation_key", keys["Attestation_key"], autokey);
            }
            if (keys.ContainsKey("MGK_KEY"))
            {
                if (cfg_writedone.MGKWrite_YesNo)
                    SetCheckboxStatus(WriteMGK, true);
                UpdateKeyCount("MGK_KEY", keys["MGK_KEY"], autokey);
            }
            if (keys.ContainsKey("Fairplay_KEY"))
            {
                if (cfg_writedone.FairplayWrite_YesNo)
                    SetCheckboxStatus(WriteFairplay, true);
                UpdateKeyCount("Fairplay_KEY", keys["Fairplay_KEY"], autokey);
            }
            if (keys.ContainsKey("ECP_KEY"))
            {
                if (cfg_writedone.ECPWrite_YesNo)
                    SetCheckboxStatus(WriteECP, true);
                UpdateKeyCount("ECP_KEY", keys["ECP_KEY"], autokey);
            }
            if (keys.ContainsKey("WiFi_MAC"))
            {
                if (cfg_writedone.WifiMacWrite_YesNo)
                    SetCheckboxStatus(WriteWifiMac, true);
                UpdateKeyCount("WiFi_MAC", keys["WiFi_MAC"], autokey);
            }
            if (keys.ContainsKey("BT_MAC"))
            {
                if (cfg_writedone.BTMacWrite_YesNo)
                    SetCheckboxStatus(WriteBTMac, true);
                UpdateKeyCount("BT_MAC", keys["BT_MAC"], autokey);
            }
            if (keys.ContainsKey("LEK"))
            {
                if (cfg_writedone.LEKWrite_YesNo)
                    SetCheckboxStatus(WriteLEK, true);
                UpdateKeyCount("LEK", keys["LEK"], false);
            }
            if (keys.ContainsKey("PEK"))
            {
                if (cfg_writedone.PEKWrite_YesNo)
                    SetCheckboxStatus(WritePEK, true);
                UpdateKeyCount("PEK", keys["PEK"], false);
            }
            if (keys.ContainsKey("PlayReady_key"))
            {
                if (cfg_writedone.PlayreadyWrite_YesNo)
                    SetCheckboxStatus(WritePlayready, true);
                UpdateKeyCount("PlayReady_key", keys["PlayReady_key"], false);
            }
            if (keys.ContainsKey("Hashkey"))
            {
                if (cfg_writedone.HashWrite_YesNo)
                    SetCheckboxStatus(WriteHash, true);
                UpdateKeyCount("Hashkey", keys["Hashkey"], false);
            }
            if (keys.ContainsKey("YouTube_KEY"))
            {
                if (cfg_writedone.YouTubeWrite_YesNo)
                    SetCheckboxStatus(WriteYouTube, true);
                UpdateKeyCount("YouTube_KEY", keys["YouTube_KEY"], false);
            }
            if (keys.ContainsKey("DSN"))
            {
                if (cfg_writedone.DSNWrite_YesNo)
                    SetCheckboxStatus(WriteDSN, true);
            }
            if (keys.ContainsKey("edid_pid"))
            {
                if (cfg_writedone.EDIDPIDWrite_YesNo)
                    SetCheckboxStatus(WriteEDIDPID, true);
            }
            if (keys.ContainsKey("edid_model_name"))
            {
                if (cfg_writedone.EDIDModeNameWrite_YesNo)
                    SetCheckboxStatus(WriteEDIDName, true);
            }
            if (keys.ContainsKey("ACAS_KEY"))
            {
                if (cfg_writedone.ACASKeyWrite_YesNo)
                    SetCheckboxStatus(WriteACASKey, true);
                UpdateKeyCount("ACAS_KEY", keys["ACAS_KEY"], false);
            }
            if (keys.ContainsKey("DAK"))
            {
                if (cfg_writedone.DAKWrite_YesNo)
                    SetCheckboxStatus(WriteDAK, true);
                UpdateKeyCount("DAK", keys["DAK"], false);
            }
            if (keys.ContainsKey("FVP"))
            {
                if (cfg_writedone.FVPWrite_YesNo)
                    SetCheckboxStatus(WriteFVP, true);
            }
            return true;
        }

        public bool UpdateKeyCountEx(string key, ref Dictionary<string, string> keys, bool autokey)
        {
            if (keys.ContainsKey(key))
                return UpdateKeyCount(key, keys[key], autokey);

            return false;
        }

        /// <summary>
        /// 获取key数量，更新Keycount
        /// </summary>
        /// <param name="key">key种类</param>
        /// <param name="keytype">key的具体类型</param>
        /// <returns></returns>
        public bool UpdateKeyCount(string key, string keytype, bool autokey)
        {
            string url = midListNow.host;
            string url1;
            string count;
            string code;
            string desc;
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.Default,
                Method = "post",
                ContentType = "application/x-www-form-urlencoded"
            };
            switch (key)
            {
                case "DeviceID":
                    {
                        url1 = url + "/statdeviceid.do?";
                        item.URL = url1;
                        item.Postdata = "devicetype=tcl_unknown_model";
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetDeviceID count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(DIDCount, count, 2);
                                else
                                    SetKeyCountStatus(DIDCount, count, 0);
                                if (autokey && WriteDID.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, "tcl_unknown_model");
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);

                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, "tcl_unknown_model");
                                }
                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse DID count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(DIDCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get DID count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(DIDCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "MAC":
                    {
                        url1 = url + "/statmac.do?";
                        item.URL = url1;
                        item.Postdata = "typeString=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetMac count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(MacCount, count, 2);
                                else
                                    SetKeyCountStatus(MacCount, count, 0);
                                if (autokey && WriteMac.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse Mac count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(MacCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get Mac count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(MacCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "HDCP_KEY":
                    {
                        url1 = url + "/stathdcpkey.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetHDCP_KEY count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(HDCPCount, count, 2);
                                else
                                    SetKeyCountStatus(HDCPCount, count, 0);
                                if (autokey && WriteHDCP.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse hdcp count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(HDCPCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get hdcp count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(HDCPCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "CI_PLUS_KEY":
                    {
                        url1 = url + "/statcikey.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetCI_PLUS_KEY count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(CICount, count, 2);
                                else
                                    SetKeyCountStatus(CICount, count, 0);
                                if (autokey && WriteCiplus.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parses ciplus count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(CICount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get ciplus count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(CICount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "WiDi":
                    {
                        url1 = url + "/statwidi.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetWiDi count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(WidiCount, count, 2);
                                else
                                    SetKeyCountStatus(WidiCount, count, 0);
                                if (autokey && WriteWiDi.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }
                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse widi count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(WidiCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get widi count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(WidiCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "Widevine_KEY":
                    {
                        url1 = url + "/statWidevineAndAttestation.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetWidevine_KEY count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(WideVineCount, count, 2);
                                else
                                    SetKeyCountStatus(WideVineCount, count, 0);
                                if (autokey && WriteWidevine.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }
                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse widevine count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(WideVineCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get widevine count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(WideVineCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "HDCP2.2_KEY":
                    {
                        url1 = url + "/stathdcpkey2.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetHDCP2.2_KEY count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(HDCP22Count, count, 2);
                                else
                                    SetKeyCountStatus(HDCP22Count, count, 0);
                                if (autokey && WriteHDCP22.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse hdcp22 count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(HDCP22Count, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get hdcp22 count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(HDCP22Count, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "NETFILX_ESN":
                    {
                        url1 = url + "/statnetfilxesn.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetNETFILX_ESN count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(ESNCount, count, 2);
                                else
                                    SetKeyCountStatus(ESNCount, count, 0);
                                if (autokey && WriteESN.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse esn count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(ESNCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get esn count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(ESNCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "Attestation_key":
                    {
                        url1 = url + "/statWidevineAndAttestation.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetAttestation_key count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(AttestationCount, count, 2);
                                else
                                    SetKeyCountStatus(AttestationCount, count, 0);
                                if (autokey && WriteAttestation.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parses attestation count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(AttestationCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get ciplus count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(AttestationCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "MGK_KEY":
                    {
                        url1 = url + "/statmgk.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetMGK count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(MGKCount, count, 2);
                                else
                                    SetKeyCountStatus(MGKCount, count, 0);
                                if (autokey && WriteMGK.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse MGK count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(MGKCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get MGK count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(MGKCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "Fairplay_KEY":
                    {
                        url1 = url + "/statfairplay.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetFairplay_KEY count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(FairplayCount, count, 2);
                                else
                                    SetKeyCountStatus(FairplayCount, count, 0);
                                if (autokey && WriteFairplay.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse Fairplay count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(FairplayCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get Fairplay count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(FairplayCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "ECP_KEY":
                    {
                        url1 = url + "/statecp.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetECP_KEY count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(ECPCount, count, 2);
                                else
                                    SetKeyCountStatus(ECPCount, count, 0);
                                if (autokey && WriteECP.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse ECP count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(ECPCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get ECP count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(ECPCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "WiFi_MAC":
                    {
                        url1 = url + "/statmac.do?";
                        item.URL = url1;
                        item.Postdata = "typeString=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetWifiMac count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(WifiMacCount, count, 2);
                                else
                                    SetKeyCountStatus(WifiMacCount, count, 0);
                                if (autokey && WriteWifiMac.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse WifiMac count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(WifiMacCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get WifiMac count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(WifiMacCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "BT_MAC":
                    {
                        url1 = url + "/statmac.do?";
                        item.URL = url1;
                        item.Postdata = "typeString=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetBTMac count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(BTMacCount, count, 2);
                                else
                                    SetKeyCountStatus(BTMacCount, count, 0);
                                if (autokey && WriteBTMac.Checked)
                                {
                                    int keycount = Convert.ToInt32(count.Replace(",", ""));
                                    if (availableCount != "unknow")
                                    {
                                        if (Convert.ToInt32(availableCount) > keycount)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                        else if (keycount < 500)
                                            AutoKeyRequire(this.Handle, key, keytype);
                                    }
                                    else if (keycount < 500)
                                        AutoKeyRequire(this.Handle, key, keytype);
                                }

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse BTMac count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(BTMacCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get BTMac count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(BTMacCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "LEK":
                    {
                        url1 = url + "/statlek.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetLEK count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(LEKCount, count, 2);
                                else
                                    SetKeyCountStatus(LEKCount, count, 0);
                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse LEK count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(LEKCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get LEK count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(LEKCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "PEK":
                    {
                        url1 = url + "/statpek.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetPEK count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(PEKCount, count, 2);
                                else
                                    SetKeyCountStatus(PEKCount, count, 0);
                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse PEK count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(PEKCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get PEK count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(PEKCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "PlayReady_key":
                    {
                        url1 = url + "/statplayready.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetPlayReady_key count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(PlayreadyCount, count, 2);
                                else
                                    SetKeyCountStatus(PlayreadyCount, count, 0);

                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse PlayReady_key count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(PlayreadyCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get PlayReady_key count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(PlayreadyCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "Hashkey":
                    {
                        url1 = url + "/stathash.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetHashkey count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(HashCount, count, 2);
                                else
                                    SetKeyCountStatus(HashCount, count, 0);
                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse Hashkey count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(HashCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get Hashkey count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(HashCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "YouTube_KEY":
                    {
                        url1 = url + "/statYoutubeKey.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetYoutubehkey count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(YouTubeCount, count, 2);
                                else
                                    SetKeyCountStatus(YouTubeCount, count, 0);
                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse Youtube key count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(YouTubeCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get Youtube key count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(YouTubeCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "ACAS_KEY": // 获取ACAS KEY数量;
                    {
                        url1 = url + "/statAcasKey.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetACASkey count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(ACASKeyCount, count, 2);
                                else
                                    SetKeyCountStatus(ACASKeyCount, count, 0);
                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse ACAS key count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(ACASKeyCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get ACAS key count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(ACASKeyCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                case "DAK":
                    {
                        url1 = url + "/statdak.do?";
                        item.URL = url1;
                        item.Postdata = "type=" + keytype;
                        HttpResult result = http.GetHtml(item);
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            Log.WriteGetKeyLog("\r\nGetDAK count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                            if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                            {
                                if (count == "0")
                                    SetKeyCountStatus(DAKCount, count, 2);
                                else
                                    SetKeyCountStatus(DAKCount, count, 0);
                            }
                            else
                            {
                                CommonMethod.ReportErrormsg("Fail to parse DAK count", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                                SetKeyCountStatus(DAKCount, code + "Error", 1);
                            }
                        }
                        else
                        {
                            CommonMethod.ReportErrormsg("Fail to get DAK count", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                            SetKeyCountStatus(DAKCount, result.StatusDescription, 1);
                            return false;
                        }
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
            return true;
        }


        /// <summary>
        /// 获取订单可用key余量
        /// </summary>
        /// <param name="order">订单号</param>
        /// <returns></returns>
        public bool GetOrderRemainKeyCount(string order)
        {
            string url = midListNow.host;
            string url1;
            string count;
            string code;
            string desc;
            if (!CommonMethod.HTTPChecker(url))
                return false;
            HttpHelper http = new HttpHelper();
            HttpItem item = new HttpItem()
            {
                Encoding = Encoding.Default,
                Method = "post",
                ContentType = "application/x-www-form-urlencoded",
                Timeout = 3000
            };
            url1 = url + "/getAvailableKeyCount.do?";
            item.URL = url1;
            item.Postdata = "ordernum=" + order;
            HttpResult result = http.GetHtml(item);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Log.WriteGetKeyLog("\r\nGetOrderRemainKeyCount count:\r\n" + item.URL + "\r\n" + item.Postdata + "\r\n" + result.Html);
                if (Xmlconfig.KeyCountXml(result.Html, "response", "count", out code, out desc, out count))
                {
                    availableCount = count.Replace(",", "");
                }
                else
                {
                    availableCount = "unknow";
                    CommonMethod.ReportErrormsg("Fail to parse GetOrderRemainKeyCount", desc + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                }
            }
            else
            {
                availableCount = "unknow";
                CommonMethod.ReportErrormsg("Fail to get GetOrderRemainKeyCount", result.StatusDescription + "\r\n" + result.Html + "\r\nAddress: " + item.URL + "\r\nPostdata: " + item.Postdata, errorDBNow);
                return false;
            }
            return true;
        }


        /// <summary>
        /// 按键触发在线抄写
        /// 注意：此按键的作用是给不需要输入SN号的工厂使用;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBtnClickStart(object sender, EventArgs e)
        {
            SN = "";    // SN置为空,用于不需要扫码SN的某些工厂;
            keyInfo = new KeyInfo();
            if (preloadNow)
            {
                MessageBox.Show(LResource.PreloadError, LResource.Error);
                return;
            }
            SetInitialStatus();
            BtnClickstart.Enabled = false;
            SNText.Enabled = false;
            Onlinemode();
        }

        /// <summary>
        /// 在线获取key的方式抄写
        /// </summary>
        public void Onlinemode()
        {
            keyInfo.DID.enable = WriteDID.Checked = (WriteDID.Checked && m_writedid.Text != LResource.Skip);
            keyInfo.Mac.enable = WriteMac.Checked = (WriteMac.Checked && m_writemac.Text != LResource.Skip);
            keyInfo.HDCP.enable = WriteHDCP.Checked = (WriteHDCP.Checked && m_writehdcp.Text != LResource.Skip);
            keyInfo.HDCP22.enable = WriteHDCP22.Checked = (WriteHDCP22.Checked && m_writehdcp22.Text != LResource.Skip);
            keyInfo.Widevine.enable = WriteWidevine.Checked = (WriteWidevine.Checked && m_writewidevine.Text != LResource.Skip);
            keyInfo.ESN.enable = WriteESN.Checked = (WriteESN.Checked && m_writeesn.Text != LResource.Skip);
            keyInfo.CI_plus.enable = WriteCiplus.Checked = (WriteCiplus.Checked && m_writeci.Text != LResource.Skip);
            keyInfo.Attestation.enable = WriteAttestation.Checked = (WriteAttestation.Checked && m_writeattestation.Text != LResource.Skip);
            keyInfo.MGK.enable = WriteMGK.Checked = (WriteMGK.Checked && m_writeMGK.Text != LResource.Skip);
            keyInfo.WiFi_MAC.enable = WriteWifiMac.Checked = (WriteWifiMac.Checked && m_writeWifiMac.Text != LResource.Skip);
            keyInfo.BT_MAC.enable = WriteBTMac.Checked = (WriteBTMac.Checked && m_writeBTMac.Text != LResource.Skip);
            keyInfo.ECP.enable = WriteECP.Checked = (WriteECP.Checked && m_writeECP.Text != LResource.Skip);
            keyInfo.LEK.enable = WriteLEK.Checked = (WriteLEK.Checked && m_writeLEK.Text != LResource.Skip);
            keyInfo.PEK.enable = WritePEK.Checked = (WritePEK.Checked && m_writePEK.Text != LResource.Skip);
            keyInfo.Playready.enable = WritePlayready.Checked = (WritePlayready.Checked && m_writePlayready.Text != LResource.Skip);
            keyInfo.Hashkey.enable = WriteHash.Checked = (WriteHash.Checked && m_writeHash.Text != LResource.Skip);
            keyInfo.YouTube_KEY.enable = WriteYouTube.Checked = (WriteYouTube.Checked && m_writeYouTube.Text != LResource.Skip);
            keyInfo.EDIDPid.enable = WriteEDIDPID.Checked = (WriteEDIDPID.Checked && m_writeEDIDPID.Text != LResource.Skip);
            keyInfo.EDIDModelName.enable = WriteEDIDName.Checked = (WriteEDIDName.Checked && m_writeEDIDName.Text != LResource.Skip);
            keyInfo.ACASKey_Data.enable = WriteACASKey.Checked = (WriteACASKey.Checked && m_writeACASKey.Text != LResource.Skip);
            keyInfo.DAK.enable = WriteDAK.Checked = (WriteDAK.Checked && m_writeDAK.Text != LResource.Skip);
            keyInfo.FVP.enable = WriteFVP.Checked = (WriteFVP.Checked && m_writeFVP.Text != LResource.Skip);
            keyInfo.DSN.enable = WriteDSN.Checked = (WriteDSN.Checked && m_writeDSN.Text != LResource.Skip);
            //keyInfo.Dolby.enable = WriteDolby.Checked = (WriteDolby.Checked && m_writeDolby.Text != LResource.Skip);

            bool preloadresult = false;

            preloadresult = true;
            timer1.Start();
            UpdateKeys(midListNow.keytype, true);
            WritekeyThread = new Thread(Writekey);
            WritekeyThread.Start();
            if (!preloadresult)
            {
                SNText.Enabled = true;
            }
        }

        /// <summary>
        /// 更新订单抄写数量
        /// </summary>
        /// <returns></returns>
        public bool UploadCopyCount()
        {
            return (SQLiteHelper.UpdateProductionNum(errorDBNow, orderNow));
        }

        /// <summary>
        /// 获取定制化抄写信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBtnOtherView(object sender, EventArgs e)
        {
            if (midListNow.rokuCustomer != null)
                MessageBox.Show("Roku TV\r\n" + "Brand:" + midListNow.rokuCustomer.brand + "\r\nOEM Model:" + midListNow.rokuCustomer.oemmodel + "\r\nDate:" + midListNow.rokuCustomer.productiondate + "\r\nRegion:" + midListNow.rokuCustomer.region + "\r\nPhone:" + midListNow.rokuCustomer.supportphone + "\r\nUrl:" + midListNow.rokuCustomer.supporturl + "\r\nRemote Type:" + midListNow.rokuCustomer.remotetype, LResource.ProductMsg);
            else
                MessageBox.Show("null");
        }

        /// <summary>
        /// 获取本地key数量
        /// </summary>
        public void GetLocalKeysCount()
        {
            int didnum;
            if (GetLocalKeyCount.GetLocalDidCount(orderNow, out didnum, ref localmidList, errorDBNow))
            {
                SetCheckboxStatus(WriteDID, true);
                if (didnum != -1)
                    SetKeyCountStatus(DIDCount, didnum.ToString(), 0);
                else
                    SetKeyCountStatus(DIDCount, "Read error", 1);
            }
            int macnum;
            if (GetLocalKeyCount.GetLocalMacCount(orderNow, out macnum, ref localmidList, errorDBNow))
            {
                SetCheckboxStatus(WriteMac, true);
                if (macnum != -1)
                    SetKeyCountStatus(MacCount, macnum.ToString(), 0);
                else
                    SetKeyCountStatus(MacCount, "Read error", 1);
            }
            int hdcpnum;
            if (GetLocalKeyCount.GetLocalHDCPKEYCount(orderNow, out hdcpnum))
            {
                SetCheckboxStatus(WriteHDCP, true);
                if (hdcpnum != -1)
                    SetKeyCountStatus(HDCPCount, hdcpnum.ToString(), 0);
                else
                    SetKeyCountStatus(HDCPCount, "Read error", 1);
            }
            int hdcp22num;
            if (GetLocalKeyCount.GetLocalHDCPKEY22Count(orderNow, out hdcp22num))
            {
                SetCheckboxStatus(WriteHDCP22, true);
                if (hdcp22num != -1)
                    SetKeyCountStatus(HDCP22Count, hdcp22num.ToString(), 0);
                else
                    SetKeyCountStatus(HDCP22Count, "Read error", 1);
            }
            int esnnum;
            if (GetLocalKeyCount.GetLocalESNCount(orderNow, out esnnum))
            {
                SetCheckboxStatus(WriteESN, true);
                if (esnnum != -1)
                    SetKeyCountStatus(ESNCount, esnnum.ToString(), 0);
                else
                    SetKeyCountStatus(ESNCount, "Read error", 1);
            }
            int widevinenum;
            if (GetLocalKeyCount.GetLocalWidevineCount(orderNow, out widevinenum))
            {
                SetCheckboxStatus(WriteWidevine, true);
                if (widevinenum != -1)
                    SetKeyCountStatus(WideVineCount, widevinenum.ToString(), 0);
                else
                    SetKeyCountStatus(WideVineCount, "Read error", 1);
            }
            int cinum;
            if (GetLocalKeyCount.GetLocalCIKEYCount(orderNow, out cinum))
            {
                SetCheckboxStatus(WriteCiplus, true);
                if (cinum != -1)
                    SetKeyCountStatus(CICount, cinum.ToString(), 0);
                else
                    SetKeyCountStatus(CICount, "Read error", 1);
            }
            int mgknum;
            if (GetLocalKeyCount.GetLocalMGKCount(orderNow, out mgknum))
            {
                SetCheckboxStatus(WriteMGK, true);
                if (mgknum != -1)
                    SetKeyCountStatus(MGKCount, mgknum.ToString(), 0);
                else
                    SetKeyCountStatus(MGKCount, "Read error", 1);
            }
            int attestationnum;
            if (GetLocalKeyCount.GetLocalAttestationCount(orderNow, out attestationnum))
            {
                SetCheckboxStatus(WriteAttestation, true);
                if (attestationnum != -1)
                    SetKeyCountStatus(AttestationCount, attestationnum.ToString(), 0);
                else
                    SetKeyCountStatus(AttestationCount, "Read error", 1);
            }
            int fairplaynum;
            if (GetLocalKeyCount.GetLocalFairplayCount(orderNow, out fairplaynum))
            {
                SetCheckboxStatus(WriteFairplay, true);
                if (fairplaynum != -1)
                    SetKeyCountStatus(FairplayCount, fairplaynum.ToString(), 0);
                else
                    SetKeyCountStatus(FairplayCount, "Read error", 1);
            }

            int leknum;
            fireTVKey.LEK = GetLocalKeyCount.GetLocalFolderKeyCount(orderNow, "LEK", out leknum);

            int peknum;
            fireTVKey.PEK = GetLocalKeyCount.GetLocalFolderKeyCount(orderNow, "PEK", out peknum);

            int palyreadynum;
            fireTVKey.Playready = GetLocalKeyCount.GetLocalFolderKeyCount(orderNow, "Playready", out palyreadynum);

            int hashkeynum;
            fireTVKey.Hashkey = GetLocalKeyCount.GetLocalFolderKeyCount(orderNow, "Hashkey", out hashkeynum);
        }

        /// <summary>
        /// 抄写用时计数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            usingTime += 1;
            UsingTime_Text.Text = usingTime.ToString();
        }

        /// <summary>
        /// 取消SN扫描框聚焦
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SNText_DoubleClick(object sender, EventArgs e)
        {
            FocusMark = false;
            this.CaptionBackColorTop = Color.RoyalBlue;
            this.CaptionBackColorBottom = Color.Cyan;
            this.Refresh();
        }

        /// <summary>
        /// 强制刷新抄写线程
        /// </summary>
        private void OnBtnRefresh(object sender, EventArgs e)
        {
            usingTime = 0;
            EnableText(SNText);
            EnableButton(BtnClickstart);
            SN = "";
            keyInfo = new KeyInfo();
            SetInitialStatus();
            if (WritekeyThread != null)
            {
                if (WritekeyThread.IsAlive)
                {
                    WritekeyThread.Abort();
                    if (timer1.Enabled)
                    {
                        timer1.Stop();
                    }
                    while (WritekeyThread.ThreadState != System.Threading.ThreadState.Aborted)
                    {
                        Thread.Sleep(100);
                    }
                }
            }
            UsingTime_Text.Text = "0";
            GC.Collect();
            MessageBox.Show(LResource.RefreshPanel);
        }

        /// <summary>
        /// 显示订单key可用余量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OrderText_MouseEnter(object sender, EventArgs e)
        {
            toolTip1.SetToolTip(OrderText, LResource.AvailableKey + availableCount);
        }
    }
}
