Newer
Older
RbFreqStand / RbFreqStandMeasure / counter / CounterCtrlForm.cs
yxw on 19 May 2021 34 KB 计数器启动后禁用按钮
using Casic.Birmm.RbFreqStandMeasure.home;
using Casic.Birmm.RbFreqStandMeasure.R_DataBase.Dto;
using Casic.Birmm.RbFreqStandMeasure.R_DataBase.Model;
using Casic.Birmm.RbFreqStandMeasure.R_DataBase.Service;
using Casic.Birmm.RbFreqStandMeasure.R_DataBase.Service.Impl;
using Casic.Birmm.RbFreqStandMeasure.R_DevService.Dto;
using Casic.Birmm.RbFreqStandMeasure.R_DevService.Service;
using Casic.Birmm.RbFreqStandMeasure.R_DevService.Service.Impl;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;

namespace Casic.Birmm.RbFreqStandMeasure.counter
{
    public partial class CounterCtrlForm : UserControl
    {
        DataTable table_counterDetecInit = null;
        DeviceService deviceService = new DeviceServiceImpl();
        DictService dictService = new DictServiceImpl();
        CounterDetecInitService counterDetecInitService = new CounterDetecInitServiceImpl();

        CounterDataService counterDataService = new CounterDataServiceImpl();
        SensitivityService sensitivityService = new SensitivityServiceImpl();

        Label colStdValue = new Label();
        Label colValue = new Label();
        string devType = "";
        string devCode = "";
        string devPort = "输入A";
        long deviceId = 0;
        bool isAdd = false;
        //public static bool isDetecting = false; 

        GPIBService gPIBService = new GPIBServiceImpl();
        GPIBService tcpService = new TCPServiceImpl();

        string valueOld = "";

        #region 样式常量定影
        private readonly Color titleBackColor = Color.FromArgb(63, 132, 215); // #3F64D7
        private readonly Font titleFont = new Font("微软雅黑", 14F, FontStyle.Regular, GraphicsUnit.Pixel, 134);
        #endregion
        

        private static CounterCtrlForm _counterCtrlForm = null;

        public static CounterCtrlForm GetInstance()
        {
            if (_counterCtrlForm == null)
                _counterCtrlForm = new CounterCtrlForm();

            return _counterCtrlForm;
        }
        
        private CounterCtrlForm()
        {
            InitializeComponent();

            List<DeviceDto> list = deviceService.getAllCounter();

            comboBox_counters.DataSource = list;
            comboBox_counters.DisplayMember = "DevName";
            comboBox_counters.ValueMember = "Id";

            comboBox_detecModel.SelectedIndex = 0;

            InitTableCounter();
            LoadCounterDetecInitList();
            
            if (list != null && list.Count > 0)
            {
                string[] ids = gPIBService.getId();
                if (ids != null && ids.Length > 0)
                {
                    text_signal.Text = ids[0];
                }
                string[] ips = tcpService.getId();
                if (ips != null && ips.Length > 0)
                {
                    text_counterIp.Text = ips[0].Split(':')[2];
                }
            }
        }

        private void InitTableCounter()
        {
            dataGridView_CounterResult.DataSource = null;

            // 添加标题栏
            Panel tableHeader = new Panel
            {
                BackColor = Color.White,
                Size = new Size(710, 50),
                Location = new Point(0, 0)
            };
            tableHeader.BackColor = titleBackColor;
            dataGridView_CounterResult.Controls.Add(tableHeader);

            // 序号
            Label colIndex = new Label
            {
                Font = titleFont,
                ForeColor = Color.White,
                TextAlign = ContentAlignment.MiddleCenter,
                BackColor = titleBackColor,
                AutoSize = false,
                Text = "序号",
                Location = new Point(0, 0),
                Size = new Size(50, 50)
            };
            dataGridView_CounterResult.Controls.Add(colIndex);
            colIndex.BringToFront();

            // 仪器型号
            Label colDevType = new Label
            {
                Font = titleFont,
                ForeColor = Color.White,
                TextAlign = ContentAlignment.MiddleCenter,
                BackColor = titleBackColor,
                AutoSize = false,
                Text = "仪器型号",
                Location = new Point(48, 0),
                Size = new Size(90, 50)
            };
            dataGridView_CounterResult.Controls.Add(colDevType);
            colDevType.BringToFront();

            // 仪器编号
            Label colDevNo = new Label
            {
                Font = titleFont,
                ForeColor = Color.White,
                TextAlign = ContentAlignment.MiddleCenter,
                BackColor = titleBackColor,
                AutoSize = false,
                Text = "仪器编号",
                Location = new Point(140, 0),
                Size = new Size(90, 50)
            };
            dataGridView_CounterResult.Controls.Add(colDevNo);
            colDevNo.BringToFront();           

            // 标称值
            colStdValue = new Label
            {
                Font = titleFont,
                ForeColor = Color.White,
                TextAlign = ContentAlignment.MiddleCenter,
                BackColor = titleBackColor,
                AutoSize = false,
                Text = "输出频率",
                Location = new Point(230, 0),
                Size = new Size(100, 50)
            };
            dataGridView_CounterResult.Controls.Add(colStdValue);
            colStdValue.BringToFront();

            // 指标值
            colValue = new Label
            {
                Font = titleFont,
                ForeColor = Color.White,
                TextAlign = ContentAlignment.MiddleCenter,
                BackColor = titleBackColor,
                AutoSize = false,
                Text = "测量频率",
                Location = new Point(327, 0),
                Size = new Size(140, 50)
            };
            dataGridView_CounterResult.Controls.Add(colValue);
            colValue.BringToFront();

            // 创建日期
            Label colSensitivity = new Label
            {
                Font = titleFont,
                ForeColor = Color.White,
                TextAlign = ContentAlignment.MiddleCenter,
                BackColor = titleBackColor,
                AutoSize = false,
                Text = "灵敏度(Vpp)",
                Location = new Point(470, 0),
                Size = new Size(90, 50)
            };
            dataGridView_CounterResult.Controls.Add(colSensitivity);
            colSensitivity.BringToFront();

            Label colTime = new Label
            {
                Font = titleFont,
                ForeColor = Color.White,
                TextAlign = ContentAlignment.MiddleCenter,
                BackColor = titleBackColor,
                AutoSize = false,
                Text = "测量时间",
                Location = new Point(558, 0),
                Size = new Size(140, 50)
            };
            dataGridView_CounterResult.Controls.Add(colTime);
            colTime.BringToFront();
  
        }

        private void LoadCounterDetecInitList()
        {
            table_counterDetecInit = new DataTable();

            table_counterDetecInit.Columns.Add("index", Type.GetType("System.String"));
            table_counterDetecInit.Columns.Add("devType", Type.GetType("System.String"));
            table_counterDetecInit.Columns.Add("devNo", Type.GetType("System.String"));
            table_counterDetecInit.Columns.Add("devPort", Type.GetType("System.String"));
            table_counterDetecInit.Columns.Add("stdValue", Type.GetType("System.String"));
            table_counterDetecInit.Columns.Add("value", Type.GetType("System.String"));
            table_counterDetecInit.Columns.Add("sensitivity", Type.GetType("System.String"));
            table_counterDetecInit.Columns.Add("logTime", Type.GetType("System.String"));
            table_counterDetecInit.Columns.Add("initId", Type.GetType("System.Int32"));
            table_counterDetecInit.Columns.Add("counterDataId", Type.GetType("System.Int64"));

            if (comboBox_counters.Text != "")
            {
                List<DeviceDto> list = deviceService.search(comboBox_counters.Text, "", "", "", "", "");
                if (null != list && list.Count > 0)
                {
                    devType = list[0].DevTypeName;
                    devCode = list[0].DevCode;
                }

                string type = comboBox_detecModel.Text.Equals("频率测量") ? "1" : "2";
                //查询历史检测数据
                List<CounterData> counterDataList = counterDataService.getHistory(deviceId, "", type);
                if (null != counterDataList && counterDataList.Count > 0)
                {
                    int index = 1;
                    foreach (CounterData counterData in counterDataList)
                    {
                        table_counterDetecInit.Rows.Add(index, devType, devCode, devPort, counterData.OutValue, counterData.Value, counterData.Sensitivity, counterData.LogTime, -1, counterData.Id);
                        index++;
                    }
                }
                else
                {
                    // 获取初始数据
                    List<CounterDetecInit> queryList = counterDetecInitService.getAll();
                    if (null != queryList && queryList.Count > 0)
                    {
                        int index = 1;
                        foreach (CounterDetecInit counterDetecInit in queryList)
                        {
                            if (comboBox_detecModel.Text.Equals("周期测量"))
                            {
                                table_counterDetecInit.Rows.Add(index, devType, devCode, devPort, counterDetecInit.Cycle, "", "", "", counterDetecInit.Id, -1);
                            }
                            else
                            {
                                table_counterDetecInit.Rows.Add(index, devType, devCode, devPort, counterDetecInit.Frequency, "", "", "", counterDetecInit.Id, -1);
                            }
                            index++;
                        }
                    }
                }

                dataGridView_CounterResult.DataSource = table_counterDetecInit;

                dataGridView_CounterResult.Columns[8].Visible = false;
                dataGridView_CounterResult.Columns[9].Visible = false;
                dataGridView_CounterResult.Columns[3].Visible = false;

                // width=714px
                dataGridView_CounterResult.Columns[0].Width = 50;
                dataGridView_CounterResult.Columns[1].Width = 90;
                dataGridView_CounterResult.Columns[2].Width = 90;
                dataGridView_CounterResult.Columns[4].Width = 100;
                dataGridView_CounterResult.Columns[5].Width = 140;
                dataGridView_CounterResult.Columns[6].Width = 90;
                dataGridView_CounterResult.Columns[7].Width = 140;

                dataGridView_CounterResult.Columns[0].ReadOnly = true;
                dataGridView_CounterResult.Columns[1].ReadOnly = true;
                dataGridView_CounterResult.Columns[2].ReadOnly = true;
                dataGridView_CounterResult.Columns[3].ReadOnly = true;
                dataGridView_CounterResult.Columns[4].ReadOnly = true;
                dataGridView_CounterResult.Columns[5].ReadOnly = true;
                dataGridView_CounterResult.Columns[6].ReadOnly = true;
                dataGridView_CounterResult.Columns[7].ReadOnly = true;

            }
        }

        private void btn_downCounterList_Click(object sender, EventArgs e)
        {
            comboBox_counters.DroppedDown = true;
        }

        private void comboBox_counters_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox_counters.Text = ((DeviceDto)comboBox_counters.SelectedItem).DevName;
            deviceId = ((DeviceDto)comboBox_counters.SelectedItem).Id;
            LoadCounterDetecInitList();
           
            if (tcpService.getId() != null && tcpService.getId().Length > 0)
            {
                text_counterIp.Text = tcpService.getId()[0].Split(':')[2];
            }

        }

        private void btn_dropDetecModel_Click(object sender, EventArgs e)
        {
            comboBox_detecModel.DroppedDown = true;
        }

        private void comboBox_detecModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox_detecModel.Text = comboBox_detecModel.SelectedItem.ToString();
            if (comboBox_detecModel.Text.Equals("频率测量"))
            {
                colStdValue.Text = "输出频率";
                colValue.Text = "测量频率";

            }
            else if (comboBox_detecModel.Text.Equals("周期测量"))
            {
                colStdValue.Text = "输出周期";
                colValue.Text = "测量周期";
            }

            LoadCounterDetecInitList();
        }

        private void dataGridView_CounterResult_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 4|| e.ColumnIndex == 5 || e.ColumnIndex == 6 || e.ColumnIndex == 7)
            {
                dataGridView_CounterResult.Rows[e.RowIndex].Cells[e.ColumnIndex].ReadOnly = false;//将当前单元格设为可读
                dataGridView_CounterResult.CurrentCell = dataGridView_CounterResult.Rows[e.RowIndex].Cells[e.ColumnIndex];//获取当前单元格
                dataGridView_CounterResult.BeginEdit(true);//将单元格设为编辑状态
            }
            if (e.ColumnIndex == 4)
            {
                valueOld = dataGridView_CounterResult.CurrentCell.Value.ToString();
            }

        }
        

        private void benDelete_Click(object sender, EventArgs e)
        {
            if (!(dataGridView_CounterResult.SelectedRows.Count > 0))
            {
                MessageBox.Show("请选择想要删除的记录!");
                return;
            }
            if (MessageBox.Show("确认删除选中记录?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == DialogResult.Yes)
            {
                int id = Convert.ToInt32(dataGridView_CounterResult.CurrentRow.Cells[8].Value);
                counterDetecInitService.delete(id);
                string outValue = dataGridView_CounterResult.CurrentRow.Cells[4].Value.ToString();
                string value = dataGridView_CounterResult.CurrentRow.Cells[5].Value.ToString();
                string sensitivity = dataGridView_CounterResult.CurrentRow.Cells[6].Value.ToString();
                string logTime = dataGridView_CounterResult.CurrentRow.Cells[7].Value.ToString();                
                counterDataService.delete(deviceId, outValue, logTime);
                
                //deviceService.delete(Convert.ToInt32(dataGridView_DevList.Rows[dataGridView_DevList.CurrentRow.Index].Cells[8].Value));
                MessageBox.Show("删除成功", "提示");
                LoadCounterDetecInitList();

            }
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (comboBox_counters.Text.Equals(""))
            {
                MessageBox.Show("请先选择待检测计数器");
                return;
            }

            isAdd = true;
            int index = table_counterDetecInit.Rows.Count;
            table_counterDetecInit.Rows.Add(index+1, devType, devCode, devPort, "", "", "", "", -1, -1);

            //dataGridView_CounterResult.dat
             dataGridView_CounterResult.Rows[index].Cells[4].ReadOnly = false;//将当前单元格设为可读
             dataGridView_CounterResult.CurrentCell = dataGridView_CounterResult.Rows[index].Cells[4];//获取当前单元格
             dataGridView_CounterResult.BeginEdit(true);//将单元格设为编辑状态
             valueOld = dataGridView_CounterResult.CurrentCell.Value.ToString();


        }

        private void roundButton1_Click(object sender, EventArgs e)
        {

        }

        private string freAndCycle(string val)
        {
            string input = val;
            string output = "";
            double inputNumberFre = 0.0;
            double inputMumberCye = 0.0;
            if (input.Contains("Hz"))
            {                
                if (input.Contains("kHz"))
                {
                    inputNumberFre = Convert.ToDouble(Convert.ToDouble(input.Substring(0, input.Length - 3)) * 1000);
                }
                else if (input.Contains("MHz"))
                {
                    inputNumberFre = Convert.ToDouble(Convert.ToDouble(input.Substring(0, input.Length - 3)) * 1000 * 1000);
                }
                else if (input.Contains("GHz"))
                {
                    inputNumberFre = Convert.ToDouble(Convert.ToDouble(input.Substring(0, input.Length - 3)) * 1000 * 1000);
                }
                else
                {
                    inputNumberFre = Convert.ToDouble(Convert.ToDouble(input.Substring(0, input.Length - 2)));
                    if (inputNumberFre == 1)
                    {
                        return "1s";
                    }
                }
                if (inputNumberFre == 0)
                {
                    return null;
                }
                double cyc = Double.Parse((1 / inputNumberFre)+"");
                int index = 0;
                if (cyc.ToString().Contains("E"))
                {
                    index = Convert.ToInt32(cyc.ToString().Split('E')[1].Replace("-","")) - 1;
                }
                else
                {
                    
                    foreach (char c in cyc.ToString().Split('.')[1])
                    {
                        if (c.Equals('0')) index++;
                        else break;
                    }
                }
                if (index < 2) output = cyc + "s";
                else if (index >= 2 && index < 5)
                {
                    output = cyc * 1000 + "ms";
                    if(cyc * 1000 < 1) output = cyc * 1000 * 1000 + "us";
                }
                else if (index >= 5 && index < 8)
                {
                    double outV = cyc * 1000 * 1000;
                    if(outV<1)output = cyc * 1000 * 1000 * 1000 + "ns";
                    else output = cyc * 1000 * 1000 + "us";
                }
                else if (index >= 8)
                {
                    output = cyc * 1000 * 1000 * 1000 + "ns";
                }
                
               
            }
            else if (input.Contains("s"))
            {
                if (input.Contains("ms"))
                {
                    inputMumberCye = Convert.ToDouble(input.Substring(0, input.Length - 2)) / 1000;
                }
                else if (input.Contains("us"))
                {
                    inputMumberCye = Convert.ToDouble(input.Substring(0, input.Length - 2)) / 1000 / 1000;
                }
                else if (input.Contains("ns"))
                {
                    inputMumberCye = Convert.ToDouble(input.Substring(0, input.Length - 2)) / 1000 / 1000 / 1000;
                }
                else
                {
                    inputMumberCye = Convert.ToDouble(input.Substring(0, input.Length - 1));
                    if (inputMumberCye == 1)
                    {
                        return "1Hz";
                    }
                }
                if (inputMumberCye == 0)
                {
                    return null;
                }
                double fre = 1 / inputMumberCye;
                int len = fre.ToString().Split('.')[0].Length;
                if (len > 0 && len <= 3) output = fre + "Hz";
                if (len > 3 && len <= 6) output = fre / 1000 + "kHz";
                if (len > 6 && len <= 9) output = fre / 1000 / 1000+ "MHz";
                if (len > 9) output = fre / 1000 / 1000+ "GHz";
            }

            return output;

        }


        private void btnStart_Click(object sender, EventArgs e)
        {
            if (text_counterIp.Text.Equals(""))
            {
                MessageBox.Show("请输入频率计数器IP!");
                return;
            }
            if (text_signal.Text.Equals(""))
            {
                MessageBox.Show("请输入信号源地址!");
                return;
            }

            

            dataGridView_CounterResult.ReadOnly = true;
            btn_add.Enabled = false;
            benDelete.Enabled = false;
            comboBox_counters.Enabled = false;
            comboBox_detecModel.Enabled = false;
            text_counterIp.ReadOnly = true;
            text_signal.ReadOnly = true;

            string[] arr = text_counterIp.Text.Split('.');
            if (arr.Length != 4)
            {
                MessageBox.Show("请输入正确的频率计数器IP!");
                return;
            }
            else
            {
                foreach (string ipEle in arr)
                {
                    string pattern = @"^[0-9]+$";
                    Regex regex = new Regex(pattern);
                    if (!regex.IsMatch(ipEle))
                    {
                        MessageBox.Show("请输入正确的频率计数器IP!");
                        return;
                    }
                    else
                    {
                        if (Convert.ToInt32(ipEle) < 0 || Convert.ToInt32(ipEle) > 255)
                        {
                            MessageBox.Show("请输入正确的频率计数器IP!");
                            return;
                        }
                    }
                }
            }

            //text_devName.ReadOnly = true;
            //btn_downCounterList.Enabled = false;
            btnStart.Enabled = false;
            //btn_dropDetecModel.Enabled = false;
            //textBox_detecModel.ReadOnly = true;
            //SetDevTestDlg.inDetecCounterId = deviceId;

            string type = comboBox_detecModel.Text.Equals("频率测量") ? "freq" : "period";
            string typeId = type.Equals("freq") ? "1" : "2";

            new Thread(() =>
            {
                int gpibConnection = gPIBService.open(text_signal.Text);
                if (gpibConnection == -1)
                {
                    MessageBox.Show("未连接信号源");
                    changeBox();
                    return;
                }

                int tcpConnection = tcpService.open("TCPIP0::" + text_counterIp.Text + "::INSTR");
                if (tcpConnection == -1)
                {
                    MessageBox.Show("未连接计数器");
                    changeBox();
                    return;
                }

                detecModelConf();

                // 获取数据
                List<CounterDetecInit> counterDetecInitList = counterDetecInitService.getAll();

                CounterCheckParam counterCheckParam = dictService.getCounterCheckParam();

                int index = 0;
                foreach (DataGridViewRow row in dataGridView_CounterResult.Rows)
                {
                    if (row.Index == -1)
                        break;
                    try
                    {
                        SensitivityContentParam sensitivityContentParam = new SensitivityContentParam();
                        if (type.Equals("freq"))
                        {
                            sensitivityContentParam.Freq = row.Cells[4].Value.ToString();
                            sensitivityContentParam.CheckModel = "0";
                        }
                        else
                        {
                            sensitivityContentParam.Period = row.Cells[4].Value.ToString();
                            sensitivityContentParam.CheckModel = "1";
                        }


                        int re = sensitivityService.beginTest(type, gPIBService, tcpService, counterCheckParam, ref sensitivityContentParam);//0:成功;-1:失败
                        string value = "";
                        if (re == 0)
                        {
                            value = type.Equals("freq") ? sensitivityContentParam.ReFreq : sensitivityContentParam.RePeriod;
                        }

                        long dataId = counterDataService.add(deviceId, row.Cells[4].Value.ToString(), value, sensitivityContentParam.VolTage, sensitivityContentParam.CheckTime.ToString("yyyy-MM-dd HH:mm:ss"), typeId);
                        table_counterDetecInit.Rows[index][8] = dataId;
                        row.Cells[5].Value = value;
                        row.Cells[6].Value = sensitivityContentParam.VolTage;
                        row.Cells[7].Value = sensitivityContentParam.CheckTime.ToString("yyyy-MM-dd HH:mm:ss");

                        //dataGridView_CounterResult.Refresh();
                        index++;
                    }
                    catch(Exception ex)
                    {
                        string str = ex.Message;
                    }
                }

                changeBox();

                gPIBService.close();
                tcpService.close();
            }).Start();

            
        }

        private void changeBox()
        {
            Invoke(new MethodInvoker(delegate ()
            {
                SetDevTestDlg.inDetecCounterId = -1;
                btnStart.Enabled = true;
                comboBox_counters.Enabled = true;
                comboBox_detecModel.Enabled = true;
                text_counterIp.ReadOnly = false;
                text_signal.ReadOnly = false;
            }));

            dataGridView_CounterResult.ReadOnly = false;
            btn_add.Enabled = true;
            benDelete.Enabled = true;
            //isDetecting = false;
        }

        private void dataGridView_CounterResult_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int id = Convert.ToInt32(dataGridView_CounterResult.Rows[e.RowIndex].Cells[8].Value);
            string value = dataGridView_CounterResult.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();

            try
            {
                if (e.ColumnIndex == 4)
                {
                    if (String.IsNullOrEmpty(value))
                    {
                        MessageBox.Show("输出" + comboBox_detecModel.Text.Substring(0, 2) + "不能为空,操作失败!");
                        if (isAdd) table_counterDetecInit.Rows.RemoveAt(table_counterDetecInit.Rows.Count - 1);
                        else
                        {
                            dataGridView_CounterResult.CurrentCell.Value = valueOld;
                            valueOld = "";
                        }
                        return;
                    }
                    else
                    {
                        if (comboBox_detecModel.Text.Equals("频率测量"))
                        {
                            if (!checkFreq(value) || freAndCycle(value) == null)
                            {
                                MessageBox.Show("请输入正确的带单位的频率值(Hz\\kHz\\MHz\\GHz)");
                                if (isAdd) table_counterDetecInit.Rows.RemoveAt(table_counterDetecInit.Rows.Count - 1);
                                else
                                {
                                    dataGridView_CounterResult.CurrentCell.Value = valueOld;
                                    valueOld = "";
                                }

                                return;
                            }
                        }
                        else
                        {
                            if (!checkCyc(value) || freAndCycle(value) == null)
                            {
                                MessageBox.Show("请输入正确的带单位的周期值(s\\ms\\us\\ns)");
                                if (isAdd) table_counterDetecInit.Rows.RemoveAt(table_counterDetecInit.Rows.Count - 1);
                                else
                                {
                                    dataGridView_CounterResult.CurrentCell.Value = valueOld;
                                    valueOld = "";
                                }
                                

                                return;
                            }
                        }
                    }

                    string freq = "";
                    string cycle = "";
                    if (comboBox_detecModel.Text.Equals("频率测量"))
                    {
                        freq = value;
                        cycle = freAndCycle(freq);
                    }
                    else
                    {
                        cycle = value;
                        freq = freAndCycle(cycle);
                    }
                    long initId = counterDetecInitService.addOrUpdate(freq, cycle);
                    dataGridView_CounterResult.Rows[e.RowIndex].Cells[8].Value = initId;
                }

                else if (e.ColumnIndex == 5)
                {
                    if (!String.IsNullOrEmpty(value))
                    {
                        if (comboBox_detecModel.Text.Equals("频率测量"))
                        {
                            if (!checkFreq(value))
                            {
                                MessageBox.Show("请输入格式正确的测量频率值!");
                                return;
                            }
                        }
                        else
                        {
                            if (!checkCyc(value))
                            {
                                MessageBox.Show("请输入格式正确的测量周期值!");
                                return;
                            }
                        }
                    }
                }
                else if (e.ColumnIndex == 6)
                {
                    if (!String.IsNullOrEmpty(value))
                    {
                        string pattern = @"^[0-9.]+$";
                        Regex regex = new Regex(pattern);
                        if (!regex.IsMatch(value))
                        {
                            MessageBox.Show("请输入格式正确的灵敏度!");
                            return;
                        }
                    }
                }
                else if (e.ColumnIndex == 7)
                {
                    if (!String.IsNullOrEmpty(value))
                    {
                        try
                        {
                            DateTime.Parse(value);  //不是字符串时会出现异常                        
                        }
                        catch
                        {
                            dataGridView_CounterResult.Rows[e.RowIndex].Cells[7].Value = "";
                            MessageBox.Show("请输入格式正确的时间!");
                            return;
                        }
                    }
                }
            }
            catch (Exception ex) { }
            finally
            {
                if (!isAdd)
                {
                    string valueTime = dataGridView_CounterResult.Rows[e.RowIndex].Cells[7].Value.ToString();

                    if (!String.IsNullOrEmpty(value) && e.ColumnIndex != 4 && String.IsNullOrEmpty(valueTime)) dataGridView_CounterResult.Rows[e.RowIndex].Cells[7].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    updateDatabase();
                }
                else
                { isAdd = false; }
            }
        }
        private bool checkFreq(string val)
        {
            string value = val;
            string pattern = @"^[0-9.]+$"; //@"/^((([^0][0-9]+|0)\.([0-9]{1,20}))$)|^(([1-9]+)\.([0-9]{1,20})$)/"; //@"^[0-9.]+$";
            Regex regex = new Regex(pattern);
            if (val.Contains(".") && ((val.IndexOf('.') != val.LastIndexOf('.'))|| val.IndexOf('.')==0 || val.LastIndexOf('.')==val.Length)) return false;
            if (val.Contains("E") && ((val.IndexOf('E') != val.LastIndexOf('E')) || val.IndexOf('E') == 0 || val.LastIndexOf('E') == val.Length)) return false;

            if (!value.Contains("Hz") && !value.Contains("kHz") && !value.Contains("MHz") && !value.Contains("GHz"))
            {
                return false;
            }
            else
            {
                if (value.Contains("E")) value = value.Replace("E", "");
                if (value.Contains("kHz")) value = value.Replace("kHz", "");
                else if (value.Contains("MHz")) value = value.Replace("MHz", "");
                else if (value.Contains("GHz")) value = value.Replace("GHz", "");
                else value = value.Replace("Hz", "");
                if (!regex.IsMatch(value)) return false;
            }

            return true;
        }

        private bool checkCyc(string val)
        {
            string value = val;
            string pattern = @"^[0-9.]+$";
            Regex regex = new Regex(pattern);
            if (val.Contains(".") && ((val.IndexOf('.') != val.LastIndexOf('.')) || val.IndexOf('.') == 0 || val.LastIndexOf('.') == val.Length)) return false;
            if (!value.Contains("s") && !value.Contains("ms") && !value.Contains("us") && !value.Contains("ns"))
            {
                return false;
            }
            else
            {
                if (value.Contains("ms")) value = value.Replace("ms", "");
                else if (value.Contains("us")) value = value.Replace("us", "");
                else if (value.Contains("ns")) value = value.Replace("ns", "");
                else value = value.Replace("s", "");
                if (!regex.IsMatch(value)) return false;
            }

            return true;
        }


        private void updateDatabase()
        {
            string type = comboBox_detecModel.Text.Equals("频率测量") ? "1" : "2";
            foreach (DataGridViewRow row in dataGridView_CounterResult.Rows)
            {
                if (!String.IsNullOrEmpty(row.Cells[5].Value.ToString()) || !String.IsNullOrEmpty(row.Cells[6].Value.ToString()))
                {
                    counterDataService.add(deviceId, row.Cells[4].Value.ToString(), row.Cells[5].Value.ToString(), row.Cells[6].Value.ToString(), row.Cells[7].Value.ToString(), type);
                }
            }
        }

        private void detecModelConf()
        {
            if (comboBox_detecModel.Text == "频率测量")
            {
                GPIB_TCPIP_OPERATIO.setFreqModel(tcpService);
            }
            else if (comboBox_detecModel.Text == "周期测量")
            {
                GPIB_TCPIP_OPERATIO.setPerModel(tcpService);
            }

        }

    }
}