using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using GcDevicePc.ProThread;
using GcDevicePc.Common;
using System.Threading;
using GcDevicePc.CK_UI;
using Ini.Net;
using System.Runtime.InteropServices;

namespace GcDevicePc
{
    public partial class MDIBase : Form
    {
        private int childFormNumber = 0;
        private static FormUser  _userForm;  //用户界面
        private static Formdebug _debugForm;  //调试界面

        private string Formstr;//窗口名称
        private string statestr;//状态信息
       // private Color stateColor=new Color();//状态颜色;
        private bool IsStateColor = false;
        System.DateTime startTime;  //系统启动时间
        TimeSpan timespan;

        bool inifilec = false;  //方法文件是否加载


        /// <summary>
        /// HMI控制接口
        /// </summary>
        HMIControl hmiopt;

        /// <summary>
        /// HMI数据获取接口
        /// </summary>
        GcDataTh mymodbus;

        /// <summary>
        /// Modbus Slave 变量
        /// </summary>
        GCModbusSlave Slavetest;

        /// <summary>
        /// Modbus Slave 485 变量
        /// </summary>
        GCModbusSlave485 Slave485test;

        /// <summary>
        /// 数据接收
        /// </summary>
        DataRcv mytcptest = new DataRcv();

        /// <summary>
        /// 处理数据接口
        /// </summary>
        CKvocUpdata dataVOC = new CKvocUpdata();

        #region Author by zjx
        /// <summary>
        /// 组件初始化
        /// </summary>
        private void DllInit()
        {
            try
            {
                if (CKVocAnalyzer.Config.Instance.ReadPath())
                {
                    CKVocAnalyzer.VOCEntityConfig.Instance.vocinit();
                    CKVocAnalyzer.Config.Instance.ReadAxisRange();
                    LogOperate.LogInit.Instance.path = CKVocAnalyzer.GlobalCKV.FolderLog;
                    LogOperate.LogInit.Instance.Init();
                    CKVocAnalyzer.GlobalCKV.tcpservice.tcpStart(CKVocAnalyzer.GlobalCKV.hostadd, CKVocAnalyzer.GlobalCKV.tcpport);
                    //自动删除
                    SpaceM.SpaceThread sthread = new SpaceM.SpaceThread(CKVocAnalyzer.GlobalCKV.HistDataPath,CKVocAnalyzer.GlobalCKV.SpaceSize,CKVocAnalyzer.GlobalCKV.SpaceTimes);
                    sthread.SpaceStart();

                    Log.Info("System Init Success");
                }
                else
                {
                    Log.Error("System Init Failed, Plesae Check Config File");
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }
        #endregion


        /// <summary>
        /// 构造函数
        /// </summary>
        public MDIBase()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
        }


        /// <summary>
        /// 主窗口载入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MDIBase_Load(object sender, EventArgs e)
        {
            DllInit();

            InitConfig();

            _debugForm = new Formdebug();
            _debugForm.MdiParent = this;
            _debugForm.Dock = DockStyle.Fill;
            _debugForm.Show();

            // debugForm.Hide();
            _userForm = new FormUser();
            _userForm.MdiParent = this;
            _userForm.Dock = DockStyle.Fill;
            _userForm.Show();

            // debugForm.Show();

            Formstr = "用户窗口";
            startTime = DateTime.Now;
          //  toolStripStatusLabeSystme.Text = string.Format("状态：{0}", Formstr);

            timespan = System.DateTime.Now - startTime;
            toolStripStatusLabelusertime.Text = String.Format("运行时间：{0}", timespan.Days.ToString() + "天" + timespan.Hours.ToString() + "时" + timespan.Minutes.ToString() + "分" + timespan.Seconds.ToString() + "秒");

            //显示方法名称
            if (String.IsNullOrEmpty(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName))
            {
                SetMainFormMethodName("未加载");
            }
            else
            {
                SetMainFormMethodName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.Substring(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName.LastIndexOf("\\") + 1));
            }

            SetMenu(LandIn.Island);
            autopensys();

            //点火接口
            _userForm.autofire += new Fireport(fireupopt);

        }


        /// <summary>
        /// 判断是否要开启系统
        /// </summary>
        private void autopensys()
        {
            try
            {
                int opensys = 0;
                String tmpfile = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.RunFolder + "\\startup.ini";
                globaldata.starttimer = 0x7FFFFFFF;
                IniFile IniParser = new IniFile(tmpfile);

                if(IniParser.KeyExists("StartUp", "打开系统"))
                    opensys = IniParser.ReadInteger("StartUp", "打开系统");

                if ((opensys == 1 && globaldata.m_hmibuffer.gcinfo.methodstatus == 0) || globaldata.m_hmibuffer.gcinfo.methodstatus != 0)
                {
                    //autoopensys_Click();
                    open();
                }

                //if (globaldata.m_hmibuffer.gcinfo.methodstatus != 0)
                //{
                //  //  hmistatus_opensys();
                //}
            }
            catch(Exception ex)
            {
                Log.Error(ex.Message);
            }
        }
       
        private void SetMenu(bool isbool)
        {
            try
            {
                if (isbool)
                {
                    NetWorkMenu.Visible = true;
                    MethodBrowseMenuItem.Visible = true;
                    NewMethodMenu.Visible = true;
                    OpenMethodMenu.Visible = true;
                    MethodBrowseMenuItem.Visible = true;
                    CalibrationMenu.Visible = true;
                    GCConfigMenuItem.Visible = true;
                    AuxToolMenu.Visible = true;
                    ParameterSettingMenu.Visible = true;
                    DebugMainMenu.Visible = true;
                    HmiStatus.Visible = true;
                    SettingSeparator.Visible = true;

                }else
                {
                    NetWorkMenu.Visible = false;
                    MethodBrowseMenuItem.Visible = false;
                    NewMethodMenu.Visible = false;
                    OpenMethodMenu.Visible = false;
                    MethodBrowseMenuItem.Visible = false;
                    CalibrationMenu.Visible = false;
                    GCConfigMenuItem.Visible = false;
                    AuxToolMenu.Visible = false;
                    ParameterSettingMenu.Visible = false;
                    DebugMainMenu.Visible = false;
                    HmiStatus.Visible = false;
                    SettingSeparator.Visible = false;
                }

            }
            catch(Exception ex)
            {
                Log.Error(ex.Message);
            }
        }
   
        /// <summary>
        /// 更新显示栏信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 1.0.2.3  添加了周期完成后，重新绘图功能
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Text = String.Format("VOCs在线监测-1.0.2.3   {0}",Formstr);
            HmiStatus.Text = String.Format("状态：{0}", statestr);

            //  toolStripStatusLabeSystme.Text = String.Format("状态：{0}", statestr);
            timespan = System.DateTime.Now - startTime;
            toolStripStatusLabelusertime.Text = String.Format("运行时间：{0}", 
                timespan.Days.ToString() + "天" + timespan.Hours.ToString() + "时" + timespan.Minutes.ToString() + "分" + timespan.Seconds.ToString() + "秒");
           // Trace.WriteLine(string.Format("时间{0}，状态{1}", getIdleTick(),LandIn.Island),"sys");

            //监视界面活动
            if (getIdleTick()>60*30 && LandIn.Island)
            {
                
                if (_userForm != null)
                {
                    Formstr = "用户窗口";
                    _userForm.Activate();
                    //userForm.Show();
                }
                LandIn.Island = false;
                SetMenu(LandIn.Island);
                Trace.WriteLine("进入自动销户","sys");
            }
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct LASTINPUTINFO
        {
            [MarshalAs(UnmanagedType.U4)]
            public int cbSize;
            [MarshalAs(UnmanagedType.U4)]
            public uint dwTime;
        }
        [DllImport("user32.dll")]
        public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

        /// <summary>
        /// 返回持续时间  s
        /// </summary>
        /// <returns></returns>
        public long getIdleTick()
        {
            LASTINPUTINFO vLastInputInfo = new LASTINPUTINFO();
            vLastInputInfo.cbSize = Marshal.SizeOf(vLastInputInfo);
            if (!GetLastInputInfo(ref vLastInputInfo)) return 0;
            return (Environment.TickCount - (long)vLastInputInfo.dwTime)/1000;
        }




        public void SendPCCMD(bool flag)
        {
            if (flag)  //打开运行
            {
                hmiopt.WriteStopVal();
                WaitHMIFree();

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                {
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteStopVal();
                    }
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                        hmiopt.WriteSingleVal();
                    WaitHMIWork();
                }
            }
            else   //批处理
            {
                hmiopt.WriteStopVal();
                WaitHMIFree();

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                {
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                        hmiopt.WriteBatVal();

                        hmiopt.WriteStartVal();

                        WaitHMIWork();
                    }

                }
            }
        }

        public void SendSTDCMD()
        {
            hmiopt.WriteStopVal();
            WaitHMIFree();
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
            {
                hmiopt.WriteSTDBatVal();
                hmiopt.WriteStartVal();
            }
        }

        private void SetMainFormMethodName(string text)
        {
            this.toolStripStatusLabelText.Text = "当前运行方法：" + text;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 0; i < 100; i++)
            {
                if (globaldata.m_hmibuffer.gcinfo.hmistatus == 0)
                {
                    if (globaldata.OS_STOP)
                    {
                        globaldata.OS_STOP = false;
                    }

                    worker.ReportProgress(100);
                    break;
                }
                else
                {
                    if (i % 20 == 0)
                    {
                        if (globaldata.OS_STOP)
                        {
                            hmiopt.WriteEndVal();
                        }
                        else
                        {
                            hmiopt.WriteStopVal();
                        }

                    }

                    Thread.Sleep(100);
                    if (i != 99)
                        worker.ReportProgress(i);
                }

                if (worker.CancellationPending)  // 如果用户取消则跳出处理数据代码 
                {
                    e.Cancel = true;
                    break;
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
            }
            else
            {
            }
        }

        public void WaitHMIFree()
        {
            if (globaldata.m_hmibuffer.gcinfo.hmistatus != 0)
            {
                this.backgroundWorker1.RunWorkerAsync();
                WaitForm form = new WaitForm(this.backgroundWorker1, "Free");
                form.ShowDialog(this);
                form.Close();
            }
               
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 0; i < 100; i++)
            {
                if (globaldata.m_hmibuffer.gcinfo.methodstatus > 0 && globaldata.m_hmibuffer.gcinfo.methodstatus < 5)
                {
                    worker.ReportProgress(100);
                    break;
                }
                else
                {
                    if (i % 20 == 0 && i != 0)
                    {
                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                            hmiopt.WriteOpenVal();

                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                            hmiopt.WriteSingleVal();


                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                        {
                            hmiopt.WriteBatVal();
                            hmiopt.WriteStartVal();
                        }
                    }

                    Thread.Sleep(100);
                    if (i <= 99)
                        worker.ReportProgress(i);
                }

                if (worker.CancellationPending)  // 如果用户取消则跳出处理数据代码 
                {
                    e.Cancel = true;
                    break;
                }
            }
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                // MessageBox.Show(e.Error.Message);
            }
            else if (e.Cancelled)
            {
            }
            else
            {
            }
        }
        public void WaitHMIWork()
        {
            if (globaldata.m_hmibuffer.gcinfo.methodstatus < 0 || globaldata.m_hmibuffer.gcinfo.methodstatus > 5)
            {
                this.backgroundWorker2.RunWorkerAsync();
                WaitForm form = new WaitForm(this.backgroundWorker2, "Work");
                form.ShowDialog(this);
                form.Close();
            }
               
        }
  
        public void SendStopCMD()
        {
            try
            {
                hmiopt.WriteStopVal();
                WaitHMIFree();
            }
            catch
            {
            }

        }

        private void InitConfig()
        {
            string tmpname = "";
            try
            {
                if (!String.IsNullOrEmpty(globaldata.connection_ip))
                {
                    Start_ConnectStatusThread();
                    try
                    {
                        globaldata.m_profileMethod.SetStatusFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_StatusName);
                        globaldata.m_profileMethod.GetDevState();
                       
                        tmpname = globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2? 
                            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName: 
                            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;

                        if (!String.IsNullOrEmpty(tmpname))
                        {
                            globaldata.show_MethodName = tmpname;
                            SetMainFormMethodName(tmpname);
                            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, tmpname.ToString());
                            globaldata.m_profileMethod.SetMethodFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);
                            globaldata.m_profileMethod.GetDevInjPortAllPara();
                            globaldata.m_profileMethod.GetSampleAllPara("前进样器");
                            globaldata.m_profileMethod.GetInjValveAllPara();
                            globaldata.m_profileMethod.GetChromAllPara();
                            globaldata.m_profileMethod.GetColTableElseAllPara();
                            globaldata.m_profileMethod.GetFidAllPara();
                            globaldata.m_profileMethod.GetTcdAllPara();
                            globaldata.m_profileMethod.GetAuxiliaryAllPara();

                            // globaldata.m_profileMethod.GetDevSignalAllPara();      
                        }
                        else
                        {
                            Log.Error("Method is Null...");
                        }

                    }
                    catch
                    {

                        Log.Error("System Init Failed");                 
                    }

                    statestr = "设备联机";
                    IsStateColor=true;

                    hmiopt = null;
                    hmiopt = new HMIControl(globaldata.connection_ip, globaldata.datamodbusport);
                    mymodbus = null;
                    mymodbus = new GcDataTh(globaldata.connection_ip, globaldata.datamodbusport);


                    Start_Thread();

                    try
                    {
                        Slavetest = new GCModbusSlave();
                        Slavetest.CModbusSlaveInit(1, 2, 3, 5);

                        Slave485test = new GCModbusSlave485(1, 9600);
                        Slave485test.CModbusSlave485Init(1, 2, 3, 5);

                    }
                    catch (Exception e)
                    {
                        Log.Error(e.Message);
                    }

                }
                else
                {
                    statestr = "未联机";
                    IsStateColor = false;
                }
            }
            catch(Exception ex)
            {
                Log.Error(ex.Message);
            }
        }


        private void Start_Thread()
        {
            // mydatasave.ChannelDataStart();
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                mymodbus.HmiStatueStart();
                mymodbus.ChannelDataStart();
            }
           
            dataVOC.CKvocUpdataStart();
            mytcptest.DataRcvStart();
        }

        private void Stop_Thread()
        {
            // mydatasave.ChannelDataStop();
        
            dataVOC.CKvocUpdataStop();
            mytcptest.DataRcvStop();

            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                mymodbus.HmiStatueStop();
                mymodbus.ChannelDataStop();
            }
        }

       /// <summary>
       /// 状态改变信号量
       /// </summary>
        ManualResetEvent datamre = new ManualResetEvent(false);
        ManualResetEvent conmre = new ManualResetEvent(false);
        ushort GCstatus = 9;
        Thread Connect_Status;


        /// <summary>
        /// HMI状态监控线程
        /// </summary>
        private void Start_ConnectStatusThread()
        {
            if (conmre != null)
            {
                conmre.Reset();
            }
            Connect_Status = new Thread(Monitor_Connect);
            Connect_Status.IsBackground = true;
            Connect_Status.Start();
        }

        /// <summary>
        /// HMI状态监控线程实现
        /// </summary>
        private void Monitor_Connect()
        {
            UInt16[] dest = new UInt16[9];
        
            ushort status_flag = 10;
            ushort status_flag_old = 10;
            ushort runtype = 0;

            while (!conmre.WaitOne(500))
            {
                Thread.Sleep(500);

                if (globaldata.m_pcbuffer.gcpcinfo.pcthreadinfo.HMI_Monitor_TH == 1)
                {
                    break;
                }

                dest[0] = globaldata.m_hmibuffer.gcinfo.batno;
                dest[1] = globaldata.m_hmibuffer.gcinfo.batruncount;
                dest[2] = globaldata.m_hmibuffer.gcinfo.oneruntime;
                dest[3] = globaldata.m_hmibuffer.gcinfo.singlerun;
                dest[4] = globaldata.m_hmibuffer.gcinfo.batrun;
                dest[5] = globaldata.m_hmibuffer.gcinfo.methodstatus;
                dest[6] = globaldata.m_hmibuffer.gcinfo.waitstart;
                dest[7] = globaldata.m_hmibuffer.gcinfo.hmistatus;
                dest[8] = globaldata.m_hmibuffer.gcinfo.runtime;

              
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                    status_flag = dest[5];
                else
                    status_flag = 10;

                GCstatus = dest[5];
                runtype = dest[7];

                globaldata.MethodRun_Statue = dest[5];
                globaldata.RunTime_Now = dest[2];
                globaldata.RunTotal_Now = dest[8];

                if (globaldata.m_hmibuffer.gcinfo.hmioffline)
                {
                    status_flag = 9;
                }


                if ((dest[5] == 4 || dest[5] == 5) && dest[7] == 4 && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue != 1)
                {

                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType = 0;
                }

                switch (runtype)
                {
                    case 0:
                       
                        DataControl_Status(dest[5], 0);
                        break;
                    case 2:
                        BAT_HeadInfo(dest[0], dest[1]);
                       
                        DataControl_Status(dest[5], 2);
                        break;
                    case 3:
                        QuickRun_HeadInfo();
                       
                        DataControl_Status(dest[5], 1);
                        break;
                    case 4:
                        SingleRun_HeadInfo();
                       
                        break;
                    default:
                        Common_HeadInfo();
                        break;
                }
                Status_Show(status_flag, ref status_flag_old);

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                {
                   
                    if (globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName != globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName)
                    {
                        string tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName;
                        string getFileName = "";
                        int ret;

                        FileServerClient mainclient = new FileServerClient();

                        try
                        {
                            mainclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);
                            if (!File.Exists(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName))
                            {
                                getFileName = tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1);
                                ret = mainclient.WtClientCopyfromServer(getFileName, globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName, globaldata.remoteFolder + "仪器方法\\");
                                Thread.Sleep(400);
                            }

                            globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName;
                            globaldata.m_profileMethod.SetMethodFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);
                            globaldata.m_profileMethod.GetDevInjPortAllPara();
                            globaldata.m_profileMethod.GetSampleAllPara("前进样器");
                            globaldata.m_profileMethod.GetInjValveAllPara();
                            globaldata.m_profileMethod.GetChromAllPara();
                            globaldata.m_profileMethod.GetColTableElseAllPara();
                            globaldata.m_profileMethod.GetFidAllPara();
                            globaldata.m_profileMethod.GetTcdAllPara();
                            globaldata.m_profileMethod.GetAuxiliaryAllPara();

                            mainclient.WtClientClose();
                        }
                        catch
                        {
                            mainclient.WtClientClose();
                        }
                    }

                }

            }
        }


        void DataControl_Status(ushort flag, ushort runtype)
        {
            switch (flag)
            {
                case 0:
                case 1:
                case 2:
                    //globaldata.work_Statue = 0;                   
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    break;
                case 3:   //已就绪               
                    break;
                case 4:
                case 5:
                    //if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 0)
                       // startbtn();
                    break;
                case 6:
                case 7:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    break;
            }
        }

        /// <summary>
        /// 控制调试按钮权限
        /// </summary>
        /// <param name="flag"></param>
        void ButtonControl_Status(ushort flag)
        {
            this.Invoke(new Action(() =>
            {
                switch (flag)
                {
                    case 0:
                    case 1:
                    case 2:
                    {
                        SingleCancel.Enabled = false;
                        SingleStop.Enabled = false;
                        SingleStart.Enabled = false;
                    }
                        break;
                    case 3: //已就绪
                    {
                        SingleCancel.Enabled = false;
                        SingleStop.Enabled = false;
                        SingleStart.Enabled = true;
                    }
                        break;
                    case 4:
                    case 5:
                    {
                        SingleCancel.Enabled = true;
                        SingleStop.Enabled = true;
                        SingleStart.Enabled = false;
                    }
                        break;
                    case 6:
                    case 7:
                    {
                        SingleCancel.Enabled = false;
                        SingleStop.Enabled = false;
                        SingleStart.Enabled = false;
                    }
                        break;
                    default:
                    {
                        SingleCancel.Enabled = false;
                        SingleStop.Enabled = false;
                        SingleStart.Enabled = false;
                    }
                        break;
                }
            }));
        }

        /// <summary>
        /// 显示系统连接状态和方法运行
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="oldflag"></param>
        void Status_Show(ushort flag, ref ushort oldflag)
        {
            string status_text = null;
            bool color_flag = true;
            switch (flag)
            {
                case 0:
                case 1:
                    status_text = "空闲中...";
                    break;
                case 2:
                    status_text = "仪器平衡中...";
                    break;
                case 3:
                    status_text = "已就绪...";
                    break;
                case 4:
                case 5:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        status_text = "方法运行中...";
                    else if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 2)
                        status_text = "方法运行中...";
                    else if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 3)
                        status_text = "方法运行中...";
                    else
                        status_text = "方法运行中...";
                    break;
                case 6:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    status_text = "后处理...";
                    break;
                case 7:
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue == 1)
                        stopbtn();
                    status_text = "后处理完毕...";
                    break;
                case 8:
                    status_text = "信号稳定中...";
                    break;
                case 9:
                    status_text = "设备断开";
                    color_flag = false;
                    break;
                default:
                    status_text = "设备连接";

                    break;
            }
            statestr = status_text;
            IsStateColor = color_flag;

            if (oldflag != flag)
            {
                oldflag = flag;
            }
        }

        void Common_HeadInfo()
        {
            string tmpFileName;
            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            invokeDelegate update_singlerunhead = () =>
            {
                SetMainFormMethodName(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1));
            };
            Invoke(update_singlerunhead);
        }

        void SingleRun_HeadInfo()
        {
            string tmpFileName;
            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            invokeDelegate update_singlerunhead = () =>
            {
                SetMainFormMethodName(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1) + " 单次运行");
            };
            Invoke(update_singlerunhead);
        }

        void QuickRun_HeadInfo()
        {
            string tmpFileName;
            tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
            invokeDelegate update_quickrunhead = () =>
            {
                SetMainFormMethodName(tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1) + " 快速运行");
            };
            Invoke(update_quickrunhead);
        }

        void BAT_HeadInfo(ushort num, ushort count)
        {
            try
            {
                INIOperation runtable = new INIOperation(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab);
                string[] key = runtable.INIGetAllItemKeys("运行表");
                string[] runnum = runtable.INIGetAllItemKeys("循环");


                if (num < key.Length)
                {
                    if ((num != 0 || count > 0))
                    {
                        if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue != 0)
                        {
                            invokeDelegate update_methodname = () =>
                            {
                                SetMainFormMethodName(runtable.INIGetStringValue("运行表", key[num], "无") + "  批处理： " + " 第" + (count + 1).ToString() + "/" + runtable.INIGetStringValue("循环", runnum[num], "无") + "次");
                            };
                            Invoke(update_methodname);


                        }
                        else
                        {
                            invokeDelegate update_methodname = () =>
                            {
                                SetMainFormMethodName(runtable.INIGetStringValue("运行表", key[num], "无") + "  批处理 ");
                            };
                            Invoke(update_methodname);
                        }
                    }

                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_BATMethodName = System.IO.Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.MethodFolder, runtable.INIGetStringValue("运行表", key[num], "无"));
                }
            }
            catch(Exception ex)
            {
                Trace.Write(ex);
            }
        }

       

        private void MDIBase_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dr = new QuitForm().ShowDialog();
           

            uint ret = 0;
            uint count = 0;

            CKVocAnalyzer.GlobalCKV.tcpservice.stop();
            _debugForm.CloseThread();

            if (dr == DialogResult.OK)  //停止系统并退出
            {
                Stop_Thread();

                count = 0;
                if (!String.IsNullOrEmpty(globaldata.connection_ip))
                {
                    globaldata.OS_STOP = true;
                    hmiopt.WriteEndVal();

                    WaitHMIFree();

                    conmre.Set();
                    globaldata.m_pcbuffer.gcpcinfo.pcthreadinfo.HMI_Monitor_TH = 1;
                    Thread.Sleep(1500);


                    count = 0;
                    ret = Slavetest.CModbusSlaveClose();
                    while (ret != 0)
                    {
                        count++;
                        ret = Slavetest.CModbusSlaveClose();
                        Thread.Sleep(100);
                        if (count > 3)
                        {
                            break;
                        }
                    }

                    count = 0;
                    ret = Slave485test.CModbusSlave485Close();
                    while (ret != 0)
                    {
                        count++;
                        ret = Slave485test.CModbusSlave485Close();
                        Thread.Sleep(100);
                        if (count > 3)
                        {
                            break;
                        }
                    }
                }

               

                try
                {
                    this.Dispose();
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                }
                catch
                {

                }
               

                //this.Dispose();
                //Thread.Sleep(1000);
                //Environment.Exit(0);
            }

            if (dr == DialogResult.Yes)  //仅退出
            {
                count = 0;
                if (!String.IsNullOrEmpty(globaldata.connection_ip))
                {
                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                        globaldata.OS_STOP = false;
                        hmiopt.WriteStopVal();

                        WaitHMIFree();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteOpenVal();
                        WaitHMIWork();
                    }

                    conmre.Set();
                    globaldata.m_pcbuffer.gcpcinfo.pcthreadinfo.HMI_Monitor_TH = 1;
                    Thread.Sleep(1500);

                    count = 0;
                    ret = Slavetest.CModbusSlaveClose();
                    while (ret != 0)
                    {
                        count++;
                        ret = Slavetest.CModbusSlaveClose();
                        Thread.Sleep(100);
                        if (count > 3)
                        {
                            break;
                        }
                    }

                    count = 0;
                    ret = Slave485test.CModbusSlave485Close();
                    while (ret != 0)
                    {
                        count++;
                        ret = Slave485test.CModbusSlave485Close();
                        Thread.Sleep(100);
                        if (count > 3)
                        {
                            break;
                        }
                    }
                }


                try
                {
                    this.Dispose();
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                }
                catch
                {

                }
            }

            if (dr == DialogResult.Cancel)  //取消
            {
                e.Cancel = true;
            }

        }

       // private bool isopen = false;
        private void open()
        {
            try
            {
                if(globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                {
                    MessageBox.Show("系统开启中......");
                    return ;
                }
                if (!String.IsNullOrEmpty(globaldata.connection_ip))
                {

                    hmiopt.WriteStopVal();
                    statestr = "系统准备中...";

                    WaitHMIFree();

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 2)
                    {
                        hmiopt.WriteBatVal();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteOpenVal();
                    }

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                    {
                        hmiopt.WriteSingleVal();
                    }

                    WaitHMIWork();

                    Thread.Sleep(500);
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = true;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                    globaldata.starttimer = 0;
                    globaldata.startimerIsSet = true;


                }
                else
                {

                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                    globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
                }

            }
            catch(Exception ex)
            {
                Trace.Write(ex);
            }
        }

        private void fireupopt(int flag, ushort time1, ushort time2)
        {
            hmiopt.FireUPWork(flag, time1, time2);
        }

        /// <summary>
        /// 调试运行表接口
        /// </summary>
        /// <param name="folder">批处理目录</param>
        /// <param name="runtablename">批处理文件名(带.ini)</param>
        private void RunTableOpt(String folder, String runtablename)
        {
            bool ret = false;
            RunTableHelper runtable = new RunTableHelper(folder, runtablename);

            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                string lfilename;
                string rfilename;
                FileServerClient rtclient = new FileServerClient();
                rtclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);

                rtclient.WtClientCopytoServer("RunMethod.ini", Path.Combine(folder, runtablename), globaldata.remoteFolder + "运行表\\");
                SendPCCMD(false);
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab = Path.Combine(folder, runtablename);
                ret = true;
            }
        }

        /// <summary>
        /// 调试运行表接口
        /// </summary>
        /// <param name="folder">批处理目录</param>
        /// <param name="runtablename">批处理文件名(带.ini)</param>
        /// <param name="count">批处理运行次数</param>
        private void RunTableOptWithCount(String folder, String runtablename, ushort count)
        {
            bool ret = false;
            RunTableHelper runtable = new RunTableHelper(folder, runtablename);

            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                string lfilename;
                string rfilename;
                FileServerClient rtclient = new FileServerClient();
                rtclient.WtClientInit(globaldata.connection_ip, globaldata.fileserverport);

                rtclient.WtClientCopytoServer("RunMethodStd.ini", Path.Combine(folder, runtablename), globaldata.remoteFolder + "运行表\\");
                hmiopt.SetBatCount(count);
                SendSTDCMD();
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_RunTab = Path.Combine(folder, runtablename);
                ret = true;
            }
        }

        /// <summary>
        /// 直接执行STD批处理
        /// </summary>
        /// <param name="count">次数</param>
        private void RunTableOptWithCount(ushort count)
        {
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                hmiopt.SetBatCount(count);
                SendSTDCMD(); 
            }
        }

        /// <summary>
        /// 更新所需，关闭HMI
        /// </summary>
        public void stopforupdatefirm()
        {
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {

                statestr = "系统停止中...";
                globaldata.OS_STOP = true;
                hmiopt.WriteEndVal();
                WaitHMIFree();
                statestr = "系统停止中...";

                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
            else
            {
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
        }

        /// <summary>
        /// 开始更新指令
        /// </summary>
        public void startupdatefirm()
        {
            hmiopt.WriteUpdateVal();
        }
        public void hair_sw(int val)
        {
            hmiopt.HAirSwitch(val);
        }
        

        private void UserLoginMenu_Click(object sender, EventArgs e)
        {
            DialogResult dr = new LandIn().ShowDialog();

            if (dr == DialogResult.OK)
            {
                if (LandIn.Island)
                {
                    if (_debugForm != null)
                    {
                        Formstr = "调试窗口";
                        _debugForm.Activate();
                    }
                    SetMenu(LandIn.Island);
                }
            }

            if (dr == DialogResult.No)
            {

            }

        }

        private void UserLogoutMenu_Click(object sender, EventArgs e)
        {
            if (_debugForm != null)
            {
                // debugForm.Hide();
            }
            if (_userForm != null)
            {
                Formstr = "用户窗口";
                _userForm.Activate();
                //userForm.Show();
            }
            LandIn.Island = false;
            SetMenu(LandIn.Island);

        }

        private void SystemStartMenu_Click(object sender, EventArgs e)
        {
            open();
        }

        private void SystemStopMenu_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {

                statestr = "系统停止中...";

                globaldata.OS_STOP = true;
                hmiopt.WriteEndVal();

                WaitHMIFree();

                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;

            }
            else
            {

                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue = false;
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 0;
            }
        }

        private void AuxToolMenu_Click(object sender, EventArgs e)
        {
            auxtool f_auxtool = new auxtool();
            int ret = 0;
            ushort[] firetime = new ushort[2];

            if(!String.IsNullOrEmpty(globaldata.connection_ip))
                ret = mymodbus.GetFireUpTime(ref firetime);

            if (f_auxtool == null)
            {
                f_auxtool = new auxtool(firetime[0], firetime[1]);

                f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);
                f_auxtool.sfupdatefirm += new StopForUpdateFirm(stopforupdatefirm);
                f_auxtool.updatefirm += new UpdateFirmCMD(startupdatefirm);
                f_auxtool.hairsw += new HAir_SW(hair_sw);


                f_auxtool.Show();
            }
            else
            {
                if (f_auxtool.IsDisposed)
                {
                    f_auxtool = new auxtool(firetime[0], firetime[1]);

                    f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);
                    f_auxtool.sfupdatefirm += new StopForUpdateFirm(stopforupdatefirm);
                    f_auxtool.updatefirm += new UpdateFirmCMD(startupdatefirm);
                    f_auxtool.hairsw += new HAir_SW(hair_sw);
                    f_auxtool.Show();

                }
                else
                {
                    f_auxtool.setfireuptime(firetime[0], firetime[1]);
                    f_auxtool.auxtoolforfireup -= new AUXTool(fireupopt);
                    f_auxtool.auxtoolforfireup += new AUXTool(fireupopt);
                    f_auxtool.sfupdatefirm -= new StopForUpdateFirm(stopforupdatefirm);
                    f_auxtool.sfupdatefirm += new StopForUpdateFirm(stopforupdatefirm);
                    f_auxtool.updatefirm -= new UpdateFirmCMD(startupdatefirm);
                    f_auxtool.updatefirm += new UpdateFirmCMD(startupdatefirm);
                    f_auxtool.hairsw -= new HAir_SW(hair_sw);
                    f_auxtool.hairsw += new HAir_SW(hair_sw);
                    f_auxtool.Show();
                }
            }
            
        }

        private void NetWorkMenu_Click(object sender, EventArgs e)
        {
            UserConfig confu = new UserConfig();
            confu.Show();
        }

        private void MethodBatMenu_Click(object sender, EventArgs e)
        {
            try
            {
                RunTables f_runtable = new RunTables();
                f_runtable.sendupdatecmd -= new SendUpdateCMD(SendPCCMD);
                f_runtable.sendupdatecmd += new SendUpdateCMD(SendPCCMD);
                f_runtable.sendstopcmd -= new SendStopCMD(SendStopCMD);
                f_runtable.sendstopcmd += new SendStopCMD(SendStopCMD);
                f_runtable.Show();

            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);

            }
        }

        private void NewMethodMenu_Click(object sender, EventArgs e)
        {
            MethodNameInputForm m_methodNameInputForm = new MethodNameInputForm();
            m_methodNameInputForm.Show();
        }

        private void OpenMethodMenu_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileDlg = new OpenFileDialog();
            fileDlg.Multiselect = false;
            fileDlg.InitialDirectory = Application.StartupPath + "\\仪器方法";
            fileDlg.Title = "请选择方法文件";
            fileDlg.Filter = "配置文件(*.ini)|*.ini";
            if (fileDlg.ShowDialog() == DialogResult.OK)
            {
                string file = fileDlg.FileName;
                // globaldata.cur_MethodName = file;
                // globaldata.cur_OpenMethodName = file;
                globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_OpenMethodName = file;
                this.inifilec = true;

                globaldata.m_profileMethod.SetMethodFullName(file);
                globaldata.m_profileMethod.GetDevState();

                if (globaldata.m_configDlg.IsDisposed)
                    globaldata.m_configDlg = new MethodConfig();

                globaldata.m_configDlg.m_InjPortDlg.reflashContent();
                globaldata.m_configDlg.m_InjSampleDlg.reflashContent();
                globaldata.m_configDlg.m_InjValveDlg.reflashContent();
                globaldata.m_configDlg.m_chromeDlg.reflashContent();
                globaldata.m_configDlg.m_RealColDlg.reflashContent();
                globaldata.m_configDlg.m_det.reflashContent();
                globaldata.m_configDlg.m_AuxDlg.reflashContent();
                // globaldata.m_configDlg.m_SignalDlg.reflashContent();

               // globaldata.m_configDlg.changenameforup -= new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
               // globaldata.m_configDlg.changenameforup += new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
                globaldata.m_configDlg.sendupdatecmd -= new ConfigDlg.SendUpdateCMD(SendPCCMD);
                globaldata.m_configDlg.sendupdatecmd += new ConfigDlg.SendUpdateCMD(SendPCCMD);
                globaldata.m_configDlg.Show();

                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType = 0;
                //globaldata.RunType = 0;
                //  globaldata.m_configDlg.m_RunTableDlg.reflashContent();
            }
        }

        private void MethodBrowseMenuItem_Click(object sender, EventArgs e)
        {
            if (globaldata.m_configDlg.Visible == true)
                return;

            if (inifilec)
            {
                globaldata.m_profileMethod.SetMethodFullName(globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName);
                globaldata.m_profileMethod.GetDevState();

                if (globaldata.m_configDlg.IsDisposed)
                    globaldata.m_configDlg = new MethodConfig();

                globaldata.m_configDlg.m_InjPortDlg.reflashContent();
                globaldata.m_configDlg.m_InjSampleDlg.reflashContent();
                globaldata.m_configDlg.m_InjValveDlg.reflashContent();
                globaldata.m_configDlg.m_chromeDlg.reflashContent();
                globaldata.m_configDlg.m_RealColDlg.reflashContent();
                globaldata.m_configDlg.m_det.reflashContent();
                globaldata.m_configDlg.m_AuxDlg.reflashContent();
                // globaldata.m_configDlg.m_SignalDlg.reflashContent();

               // globaldata.m_configDlg.changenameforup -= new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);
               // globaldata.m_configDlg.changenameforup += new ConfigDlg.ChangeMNameForUp(SetMainFormMethodName);

                globaldata.m_configDlg.sendupdatecmd -= new ConfigDlg.SendUpdateCMD(SendPCCMD);
                globaldata.m_configDlg.sendupdatecmd += new ConfigDlg.SendUpdateCMD(SendPCCMD);

                globaldata.m_configDlg.Show();

            }
            else
            {
                OpenFileDialog fileDlg = new OpenFileDialog();
                fileDlg.Multiselect = false;
                fileDlg.InitialDirectory = Application.StartupPath + "\\仪器方法";
                fileDlg.Title = "请选择方法文件";
                fileDlg.Filter = "配置文件(*.ini)|*.ini";
                if (fileDlg.ShowDialog() == DialogResult.OK)
                {
                    string file = fileDlg.FileName;
                    //  globaldata.cur_MethodName = file;
                    //globaldata.cur_OpenMethodName = file;
                    globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_OpenMethodName = file;

                    globaldata.m_profileMethod.SetMethodFullName(file);
                    globaldata.m_profileMethod.GetDevState();

                    if (globaldata.m_configDlg.IsDisposed)
                        globaldata.m_configDlg = new MethodConfig();

                    globaldata.m_configDlg.m_InjPortDlg.reflashContent();
                    globaldata.m_configDlg.m_InjSampleDlg.reflashContent();
                    globaldata.m_configDlg.m_InjValveDlg.reflashContent();
                    globaldata.m_configDlg.m_chromeDlg.reflashContent();
                    globaldata.m_configDlg.m_RealColDlg.reflashContent();
                    globaldata.m_configDlg.m_det.reflashContent();
                    globaldata.m_configDlg.m_AuxDlg.reflashContent();
                    
                    globaldata.m_configDlg.sendupdatecmd -= new ConfigDlg.SendUpdateCMD(SendPCCMD);
                    globaldata.m_configDlg.sendupdatecmd += new ConfigDlg.SendUpdateCMD(SendPCCMD);
                    globaldata.m_configDlg.Show();
                }
            }
        }

        private void HistoryDataMenu_Click(object sender, EventArgs e)
        {
            try
            {
                WaveTotalForm total = new WaveTotalForm();
                total.Show();

            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        private void CalibrationMenu_Click(object sender, EventArgs e)
        {

            try
            {
                AdjustFrom just = new AdjustFrom();
                just.Show();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        private void HistoryPicMenu_Click(object sender, EventArgs e)
        {
            try
            {
                HistChartForm hist = new HistChartForm();
                hist.Show();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

        }

        private void ConfigCreateSubMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                CreateConfig f = new CreateConfig();
                f.Show();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

          
        }

        private void ConfigShowSubMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                ShowConfig f = new ShowConfig();
                f.Show();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

        }

        private void ConfigSendSubMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                SendConfig f = new SendConfig();
                f.Show();
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }

        private void ParameterSettingMenu_Click(object sender, EventArgs e)
        {
            try
            {
                CKVocAnalyzer.SetInfoForm sf = new CKVocAnalyzer.SetInfoForm();
                sf.Show();

            }
            catch (Exception ex)
            {
                Trace.Write(ex);
            }
        }

        #region 单次处理控制
        private void startbtn()
        {
            globaldata.startflag = true;
            globaldata.stopflag = false;
            globaldata.cancelflag = false;
            globaldata.startclear = true;
            globaldata.starttimer = 0;
            globaldata.startimerIsSet = true;
            globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 1;
        }

        private void SingleStart_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true && globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {

                    if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                    {
                        hmiopt.WriteOpenVal();

                    }
                    hmiopt.WriteStartVal();

                    startbtn();
                }
            }
        }

        Thread t_checkcmd;
        public void stopbtn()
        {
            globaldata.startflag = false;
            globaldata.stopflag = true;
            globaldata.cancelflag = false;

            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 2;
            }

            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
            {
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
                {
                    hmiopt.WriteOpenVal();
                    t_checkcmd = new Thread(checkcmd);
                    t_checkcmd.IsBackground = true;
                    t_checkcmd.Start();
                }
            }
        }

        private void checkcmd()
        {
            while (globaldata.m_hmibuffer.gcinfo.methodstatus != 3)
            {
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {
                    hmiopt.WriteOpenVal();
                }
                else if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 1)
                {
                    hmiopt.WriteSingleVal();
                }
                else
                {

                }
                Thread.Sleep(1000);
            }
        }

        private void SingleStop_Click(object sender, EventArgs e)
        {
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
            {
             
                hmiopt.WriteStopVal();
                
                WaitHMIFree();

                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {
                    hmiopt.WriteOpenVal();
                }
                stopbtn();
            }
        }

        private void cancelbtn()
        {
            globaldata.startflag = false;
            globaldata.stopflag = false;
            globaldata.cancelflag = true;
            globaldata.starttimer = 0x7FFFFFFF;
            if (!String.IsNullOrEmpty(globaldata.connection_ip))
            {
                globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.work_Statue = 3;
            }

            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
            {
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
                {
                    hmiopt.WriteOpenVal();
                    t_checkcmd = new Thread(checkcmd);
                    t_checkcmd.IsBackground = true;
                    t_checkcmd.Start();
                }

            }
        }

        private void SingleCancel_Click(object sender, EventArgs e)
        {
            if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue == true)
            {
                hmiopt.WriteCancalVal();
                WaitHMIFree();
                if (globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.RunType == 0)
                {
                    hmiopt.WriteOpenVal();
                                 
                }
                cancelbtn();
            }
        }

        #endregion

        AboutForm f_showcfg;
        private void AboutMenu_Click(object sender, EventArgs e)
        {
            int ret = 0;
            ushort[] version = new ushort[12];
            ret = mymodbus.GetFireWareVersion(ref version);

            if (f_showcfg == null)
            {
                f_showcfg = new AboutForm(version);
                f_showcfg.Show();
            }
            else
            {
                if (f_showcfg.IsDisposed)
                {
                    f_showcfg = new AboutForm(version);
                    f_showcfg.Show();
                }
                else
                {
                    f_showcfg.Show();
                }

            }
        }
        /// <summary>
        /// 校准完成时间
        /// </summary>

        DateTime AutoAdjust;
        private void timerWorker_Tick(object sender, EventArgs e)
        {
            try
            {
                if (SharedSpace.MControl.SetOut && SharedSpace.MControl.SetRun == false)  //准备开始校准
                {
                    SharedSpace.MControl.errstr = null;
                    SharedSpace.MControl.zhouqi = globaldata.m_dpbuffer.ShowList.showtime.alltime;
                    Trace.WriteLine(string.Format("开始校准{0},{1}", SharedSpace.MControl.zhouqi, SharedSpace.MControl.runcount), "sys");
                    if(SharedSpace.MControl.zhouqi*SharedSpace.MControl.runcount<=SharedSpace.MControl.dateend)
                    {
                     //   RunTableOpt(SharedSpace.MControl.path, SharedSpace.MControl.Name);
                        RunTableOptWithCount(SharedSpace.MControl.path, SharedSpace.MControl.Name,100);
                    Thread.Sleep(60 * 1000);
                    SharedSpace.MControl.SetRun = true;//仪器进入校准环境
                    AutoAdjust = DateTime.Now.AddSeconds(SharedSpace.MControl.dateend);
                  
                    }else
                    {
                        SharedSpace.MControl.errstr = "校准时间不够";
                        SharedSpace.MControl.SetOut = false;
                    }
                }
                //等待校准结束
                if (DateTime.Now >= AutoAdjust && SharedSpace.MControl.SetOut && SharedSpace.MControl.SetRun)
                {
                    SharedSpace.MControl.IsEnd = true;
                  
                   // RunTableOpt(SharedSpace.MControl.defaultPath, SharedSpace.MControl.defaultName);
                    RunTableOptWithCount(SharedSpace.MControl.defaultPath, SharedSpace.MControl.defaultName, 10000);
                    Thread.Sleep(30 * 1000);
                   // RunTableOptWithCount(65534);
                    SharedSpace.MControl.SetOut = false;
                    SharedSpace.MControl.SetRun = false;
                    Trace.WriteLine("校准结束", "sys");
                }
                if (SharedSpace.MControl.forceEnd && SharedSpace.MControl.SetOut && SharedSpace.MControl.SetRun)
                {
                    SharedSpace.MControl.IsEnd = false;
                   
                    //RunTableOpt(SharedSpace.MControl.defaultPath, SharedSpace.MControl.defaultName);
                    RunTableOptWithCount(SharedSpace.MControl.defaultName, SharedSpace.MControl.defaultName, 10000);
                    Thread.Sleep(30 * 1000);
                    SharedSpace.MControl.SetOut = false;
                    SharedSpace.MControl.SetRun = false;
                    Trace.WriteLine("强制校准结束", "sys");

                }

            }
            catch (Exception ex)
            {
                Trace.Write(ex);
            }
        }

        //private void debugSubMenu_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        _424XTest test = new _424XTest();
        //        test.Show();
        //    }
        //    catch (Exception ex)
        //    {
        //        Log.Error(ex.Message);
        //    }
        //}
    }
}
