using Cognex.VisionPro;
using Cognex.VisionPro.Dimensioning;
using Cognex.VisionPro.ImageFile;
using Cognex.VisionPro.ToolBlock;
using Cognex.VisionPro.ImageProcessing;
using Cognex.VisionPro.Caliper;
using ConVX.VXData;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.Diagnostics;
using Cognex.VisionPro.PMAlign;
using WaferAdjust;


namespace WaferAlignment
{
    public partial class Form1 : Form
    {
        Camera _cam;
        SiemensS7 _s7;
        DataPostbox ImageData;
        TCP _tcp;
        
        string arSizeX = "DB7.DBD48";
        string arSizeY = "DB7.DBD52";
        string arSizeR = "DB7.DBD56";
        string arSpeedX = "DB7.DBD60";
        string arSpeedY = "DB7.DBD64";
        string arSpeedR = "DB7.DBD68";
        /// <summary>
        /// 执行模式
        /// </summary>
        string arMode = "DB7.DBW72";//
        /// <summary>
        /// 执行上面设置的动作
        /// </summary>
        string arAction = "DB7.DBX74.0";
        /// <summary>
        ///动作执行完成 
        /// </summary>
        string arOver = "DB7.DBX74.1";

        GetCircleToolBlock getCircleMachineToolBlock;
        FitCircleToolBlock FitCircleMachineToolBlock;
        TranslateCirclePoint translateCirclePoint;
        CogGraphicCollection m_graphics;

        //偏差量
        double deviationX;
        double deviationY;

        //
        string TCP_time = "0";
        string TCP_X = "0";
        string TCP_Y = "0";
        string TCP_R = "0";
        string TCP_RMS = "0";

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {

            // 连接相机
            try
            {
                _cam = new Camera();
                _cam.Connect();
                _cam.OutputImageEvent += _cam_OutputImageEvent;
                lbl_CameraState.BackColor = Color.Lime;
                lbl_CameraState.Text = "已连接";
            }
            catch (Exception ex)
            {
                lbl_CameraState.BackColor = Color.Red;
                lbl_CameraState.Text = "连接失败";
                MessageBox.Show(ex.Message);
            }
            // 连接通信
            try
            {
                _s7 = new SiemensS7("192.168.1.10");
                _s7.Connect();
                while (!_s7.OK)
                {

                }
                _s7.SetValue(arSpeedX, (float)2);//5
                _s7.SetValue(arSpeedY, (float)2);//2
                _s7.SetValue(arSpeedR, (float)360);//100
                _s7.SetValue(arSizeX, (float)1);
                _s7.SetValue(arSizeY, (float)-1);
                _s7.SetValue(arSizeR, (float)0);
                lbl_CommunState.BackColor = Color.Lime;
                lbl_CommunState.Text = "已连接";
            }
            catch (Exception ex)
            {
                lbl_CommunState.BackColor = Color.Red;
                lbl_CommunState.Text = "连接失败";
                MessageBox.Show(ex.Message);
            }
            //链接TCP通信
            try
            {
                //通信初始化
                _tcp = new TCP();
                _tcp.DataReceived += _tcp_DataReceived;
                _tcp.StartServer();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            try
            {
                // 加载VPP文件
                getCircleMachineToolBlock = new GetCircleToolBlock();
                getCircleMachineToolBlock.OnGetCircleResult += GetCircleMachineToolBlock_OnGetCircleResult;
                getCircleMachineToolBlock.OnGetNashResult += GetCircleMachineToolBlock_OnGetNashResult;
                getCircleMachineToolBlock.OnToolReady += GetCircleMachineToolBlock_OnToolReady;
                getCircleMachineToolBlock.Initialize("vpp\\GetCircleM.vpp");

                FitCircleMachineToolBlock = new FitCircleToolBlock();
                FitCircleMachineToolBlock.OnFitCircleResult += FitCircleMachineToolBlock_OnFitCircleResult;
                FitCircleMachineToolBlock.OnToolReady += FitCircleMachineToolBlock_OnToolReady;
                FitCircleMachineToolBlock.Initialize("vpp\\FitCircleM.vpp");
                translateCirclePoint = new TranslateCirclePoint();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            try
            {
                ImageData = new DataPostbox();

                //启动
                ImageData.Start();
                // 注册事件处理程序到 DeliverLetterEvent 事件中
                ImageData.DeliverLetterEvent += MonitorSpot;//查找所有点
                ImageData.ErrorEvent += ImageData_ErrorEvent;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void FitCircleMachineToolBlock_OnToolReady(bool ready)
        {
            LogHelper.LogInfo("FitCircleMachineToolBlock_OnToolReady");
        }

        private void FitCircleMachineToolBlock_OnFitCircleResult(double x, double y, double r, double rms)
        {
            TCP_X = x.ToString("F4");
            TCP_Y = y.ToString("F4");
            TCP_RMS = rms.ToString("F4");
            TCP_R = r.ToString("F4");

            deviationX = Math.Round((x - translateCirclePoint.GetRotateX()), 3);
            deviationY = Math.Round((y - translateCirclePoint.GetRotateY()), 3);

            AddPointMarker(m_graphics, x, y);
            AddPointMarker(m_graphics, translateCirclePoint.GetRotateX(), translateCirclePoint.GetRotateY(), CogColorConstants.Red);

            PointInfo nPoint = translateCirclePoint.GetNashPoint();
            if (nPoint != null)
            {
                AddPointMarker(m_graphics, nPoint.X, nPoint.Y, CogColorConstants.Yellow);
                AddLineMarker(m_graphics, x, y, x, y - r);
                AddLineMarker(m_graphics, x, y, nPoint.X, nPoint.Y, CogColorConstants.Yellow);
                angle = GetCounterClockwiseAngle360(x, y, x, y - r, nPoint.X, nPoint.Y);
                AddLabelMarker(m_graphics, angle.ToString(), x, y, CogColorConstants.Yellow);
                LogHelper.LogInfo($"nash degree:{angle}");
            }

            LogHelper.LogInfo($"X:{x}, Y:{y}, RMS:{rms}");
            LogHelper.LogInfo($"DiffX:{deviationX}, DiffY:{deviationY}, RMS:{rms}{Environment.NewLine}");
            ImageDisplay(FitCircleMachineToolBlock.FitCircleImage);
            ImageDisplay(m_graphics);
            ImageDisplayFit();
        }
        private void AddPointMarker(CogGraphicCollection graphicCollection, double x, double y, CogColorConstants color = CogColorConstants.Green)
        {
            CogPointMarker marker = new CogPointMarker();
            marker.X = x;
            marker.Y = y;
            marker.Color = color;
            marker.Interactive = false;
            graphicCollection.Add(marker);
        }
        private void AddLineMarker(CogGraphicCollection graphicCollection, double x1, double y1, double x2, double y2, CogColorConstants color = CogColorConstants.Green)
        {
            CogLineSegment line = new CogLineSegment();
            line.SetStartEnd((int)x1, (int)y1, (int)x2, (int)y2);
            line.Color = color;
            line.Interactive = false;
            graphicCollection.Add(line);
        }
        private void AddLabelMarker(CogGraphicCollection graphicCollection, string text, double x, double y, CogColorConstants color = CogColorConstants.Green)
        {
            CogGraphicLabel label = new CogGraphicLabel();
            label.Text = text;
            label.X = x;
            label.Y = y;
            label.Color = color;
            graphicCollection.Add(label);
        }
        /// <summary>
        /// 计算从 lineA 到 lineB 的逆时针有向角度（0-360度）
        /// 坐标系：向右为正，向下为正（标准屏幕坐标系）
        /// </summary>
        public double GetCounterClockwiseAngle360(double x, double y, double x1, double y1, double x2, double y2)
        {
            // 2. 获取方向向量（dy 向下为正）
            double dxA = x1 - x;
            double dyA = y1 - y;

            double dxB = x2 - x;
            double dyB = y2 - y;

            // 3. 将Y轴翻转，转换为标准数学坐标系（dy向上为正）
            //    这样 Math.Atan2 返回的就是标准数学角度（逆时针为正）
            double angleA = Math.Atan2(-dyA, dxA);  // 注意：y取负号
            double angleB = Math.Atan2(-dyB, dxB);  // 注意：y取负号

            // 4. 计算逆时针角度差（弧度）
            double angleDiff = angleB - angleA;

            // 5. 转换为角度并规范化为 [0, 360)
            double angleDegrees = angleDiff * 180.0 / Math.PI;
            angleDegrees = angleDegrees % 360.0;
            if (angleDegrees < 0) angleDegrees += 360.0;

            return Math.Round(angleDegrees, 3);
        }
        private void GetCircleMachineToolBlock_OnToolReady(bool ready)
        {
            LogHelper.LogInfo("GetCircleMachineToolBlock_OnToolReady");
        }

        private void GetCircleMachineToolBlock_OnGetNashResult(double x, double y)
        {
            translateCirclePoint.AddNashPoint(x, y);
            LogHelper.LogInfo($"Update Nash X:{x}, Y:{y}");
        }

        private void GetCircleMachineToolBlock_OnGetCircleResult(double x, double y, double r)
        {
            translateCirclePoint.AddCircleCenter(x, y, r);
            translateCirclePoint.AddCirclePoint(getCircleMachineToolBlock.PointInfos);
            LogHelper.LogInfo($"X:{x}, Y:{y}, R:{r}");
        }

        /// <summary>
        /// 接收到TCP数据时，根据接收到的数据，进行不同操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _tcp_DataReceived(object sender, DataReceivedEventArgs e)
        {
            if (InvokeRequired)
            {
                // 如果当前线程不是UI线程，则使用Invoke在UI线程上执行
                Invoke(new Action<object,DataReceivedEventArgs>(_tcp_DataReceived), sender, e);
            }
            else
            {
                if (e.Data == "T0")
                {
                    string str;
                    str = ToZero();
                    _tcp.SendData(e.ClientIp, str);
                }
                else if (e.Data == "GET")
                {
                    string str;
                    str = ToAction();
                    _tcp.SendData(e.ClientIp, str);
                }
                else if (e.Data == "RUN")
                {
                    SavePath = Path.Combine(Path.GetPathRoot(Application.ExecutablePath), "SaveImage", DateTime.Now.ToString("yyyyMMdd_HHmmss"));

                    ClearDisplay();
                    string str;
                    str = RunTest();
                    _tcp.SendData(e.ClientIp, str);
                    _tcp.SendData(e.ClientIp, "DetectionTime：" + TCP_time + " " + "X：" + TCP_X + " " + "Y：" + TCP_Y + " " + "Angle：" + TCP_R + " " + "RMS：" + TCP_RMS);
                }
            }
        }

        void _cam_OutputImageEvent(Bitmap obj)
        {
            acqNum++;
            ImageData.Mailing(new CogImage8Grey(obj));
            Images.Add(new CogImage8Grey(obj));

        }

        void ImageData_ErrorEvent(string obj)
        {
            
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (_s7 != null)
                {
                    _s7.Disconnect();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            try
            {
                if(_cam.IsStarted)
                {
                    _cam.Stop();
                }
                if (_cam.IsConnected)
                {
                    _cam.Disconnect();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            try
            {

                //停止位
                ImageData.Stop();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            try
            {
                _tcp.StopServer();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void btn_ToZero_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                splitContainer1.Invoke(new Action(() => splitContainer1.Panel2.Enabled = false));
                m_roateX = 0;
                m_roateY = 0;
                string str = "";
                str = ToZero();
                MessageBox.Show(str);

                splitContainer1.Invoke(new Action(() => splitContainer1.Panel2.Enabled = true));
            });
        }
        public string ToZero()
        {
            if (_s7 != null)
            {

                _s7.SetValue(arMode, (ushort)4);
                _s7.SetValue(arAction, true);
                Thread.Sleep(20);
                while (true)
                {
                    bool value = false;
                    if (_s7.GetValue(arOver, out value))
                    {
                        if (value)
                        {
                            _s7.SetValue(arAction, false);
                            break;
                        }
                        else
                        {
                            Thread.Sleep(20);
                            continue;
                        }
                    }
                    else
                    {
                        Thread.Sleep(20);
                        continue;
                    }
                }
                return "OK_T0";
            }
            else
            {
                return "NG_T0";
            }
        }
        private void btn_Action_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
           {
               splitContainer1.Invoke(new Action(() => splitContainer1.Panel2.Enabled = false));
               string str = "";
               str = ToAction();
               MessageBox.Show(str);

               splitContainer1.Invoke(new Action(() => splitContainer1.Panel2.Enabled = true));
           });
        }

        public string ToAction()
        {
            if (_s7 != null)
            {

                _s7.SetValue(arMode, (ushort)0);
                _s7.SetValue(arSizeX, Convert.ToSingle(nud_SizeX.Value));
                _s7.SetValue(arSizeY, Convert.ToSingle(nud_SizeY.Value));
                _s7.SetValue(arSizeR, Convert.ToSingle(nud_SizeR.Value));
                _s7.SetValue(arAction, true);
                Thread.Sleep(20);
                while (true)
                {
                    bool value = false;
                    if (_s7.GetValue(arOver, out value))
                    {
                        if (value)
                        {
                            _s7.SetValue(arAction, false);
                            break;
                        }
                        else
                        {
                            Thread.Sleep(20);
                            continue;
                        }
                    }
                    else
                    {
                        Thread.Sleep(20);
                        continue;
                    }
                }
                return "OK_GET";

            }
            else
            {
                return "NG_GET";
            }
        }

        List<CogImage8Grey> Images;
        int acqNum = 0;
        int testNum = 0;
        double angle = 0;
        Stopwatch sw_1 = new Stopwatch();//检测找点时间
        Stopwatch sw_2 = new Stopwatch();//检测拟合圆时间
        double times = 0;//整体检测时间
        private void btn_RunTest_Click(object sender, EventArgs e)
        {
            SavePath = Path.Combine(Path.GetPathRoot(Application.ExecutablePath), "SaveImage", DateTime.Now.ToString("yyyyMMdd_HHmmss"));
            m_cameraCount = Convert.ToDouble(textBox2.Text);
            m_codeCount = Convert.ToDouble(textBox3.Text);
            m_roateX = Convert.ToDouble(nud_SizeX.Value);
            m_roateY = Convert.ToDouble(nud_SizeY.Value);
            ClearDisplay();
            Task.Run(() =>
            {
                splitContainer1.Invoke(new Action(() => splitContainer1.Panel2.Enabled = false));
                string str = "";
                str = RunTest();
                MessageBox.Show(str);

                splitContainer1.Invoke(new Action(() => splitContainer1.Panel2.Enabled = true));
            });
        }

        public string RunTest()
        {
            if (!_cam.IsConnected)
            {
                return "CF_CAM";//启动检测失败，相机未连接

            }
            else
            {
                //R轴回0
                if (_s7 != null)
                {
                    _s7.SetValue(arMode, (ushort)3);//写入PLC控制模式 3 
                    Thread.Sleep(100);
                    _s7.SetValue(arAction, true);//写入PLC控制 行动开始 
                    Thread.Sleep(20);
                    while (true)//判断运动是否结束 
                    {
                        bool value = false;
                        if (_s7.GetValue(arOver, out value))//读取地址为arOver的结束数据是否成功 并返回读取结果   
                        {
                            if (value)//判断读取结束结果
                            {
                                _s7.SetValue(arAction, false);//写入PLC控制 行动结束 
                                break;
                            }
                            else
                            {
                                Thread.Sleep(20);
                                continue;
                            }
                        }
                        else
                        {
                            Thread.Sleep(20);
                            continue;
                        }
                    }
                }
                Thread.Sleep(500);

                _cam.Start();
                if (!_cam.IsStarted)
                {
                    return "SF_CAM";//启动检测失败，相机启动失败

                }
                else
                {
                    angle = 0;
                    acqNum = 0;
                    testNum = 0;
                    Images = new List<CogImage8Grey>();

                    sw_1 = new Stopwatch();//检测时间
                    sw_2 = new Stopwatch();//检测时间
                    deviationX = 0;
                    deviationY = 0;
                    times = 0;
                    //启动拍照
                    translateCirclePoint.SetRotateXY(m_roateX, m_roateY, 360 * m_cameraCount / m_codeCount);

                    if (_s7 != null)
                    {
                        //_s7.SetValue(arOver, false);
                        //_s7.SetValue(arMode, (ushort)5);//写入PLC控制模式 5 启动拍照
                        _s7.SetValue(arMode, (ushort)0);//写入PLC控制模式 0 启动拍照
                        _s7.SetValue(arSizeR, 360F);
                        //Thread.Sleep(100);
                        _s7.SetValue(arAction, true);//写入PLC控制 行动开始 

                        //Thread.Sleep(100);
                        while (true)//判断运动是否结束
                        {
                            bool value = false;
                            if (_s7.GetValue(arOver, out value))
                            {
                                if (value)
                                {
                                    _s7.SetValue(arAction, false);
                                    break;
                                }
                                else
                                {
                                    Thread.Sleep(20);
                                    continue;
                                }
                            }
                            else
                            {
                                Thread.Sleep(20);
                                continue;
                            }
                        }
                        //Thread.Sleep(100);
                    }
                }

                _cam.SoftwareGrab();
                _cam.Stop();

                while (testNum < acqNum)
                {
                    Thread.Sleep(20);
                }
                FitCircle();

                
                Task.Run(() => { Save(); });
            }
            return "OK_RUN";
        }
        private CogImage8Grey m_lastImage;
        private void MonitorSpot(CogImage8Grey outputImg)
        {
            sw_1 = new Stopwatch();//检测时间
            sw_1.Start();

            translateCirclePoint.AddCircleIndex();
            m_lastImage = outputImg;
            getCircleMachineToolBlock.Run(outputImg);

            sw_1.Stop();
            TimeSpan ts = sw_1.Elapsed;
            PointInfo pp = translateCirclePoint.GetFirstPoint();
            if (pp != null)
                DataDisplay(translateCirclePoint.GetCurrentDegree(), pp.X, pp.Y, ts.TotalMilliseconds);
            else
                DataDisplay(translateCirclePoint.GetCurrentDegree(), 0, 0, ts.TotalMilliseconds);
            testNum++;
            times += ts.TotalMilliseconds;
        }

        private void FitCircle()
        {
            sw_2 = new Stopwatch();//检测时间
            sw_2.Start();

            LogHelper.LogInfo("转换机械坐标系下圆弧各点的原始坐标：\n");
            var points = translateCirclePoint.DoTranslatePoint();
            translateCirclePoint.DoTranslateNashPoint();

            LogHelper.LogInfo("拟合机械坐标系下的圆中心：\n");
            m_graphics = new CogGraphicCollection();
            m_graphics = new CogGraphicCollection();
            foreach (PointInfo pointInfo in points)
            {
                AddPointMarker(m_graphics, pointInfo.X, pointInfo.Y);
            }

            FitCircleMachineToolBlock.Run(m_lastImage, points);

            sw_2.Stop();
            TimeSpan ts = sw_2.Elapsed;

            times += ts.TotalMilliseconds;
            TCP_time = ts.TotalMilliseconds.ToString();

            ResultDisplay(times, ts.TotalMilliseconds, TCP_X, TCP_Y, TCP_R, TCP_RMS, deviationX, deviationY, angle);
        }

        private void ResultDisplay(double Times,double Time, string X, string Y, string R, string RMS, double dX, double dY, double dR)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => ResultDisplay(Times,Time,X, Y, R, RMS, dX, dY, dR)));
                return;
            }
            txt_Times.Text = Times.ToString();
            txt_Time.Text = Time.ToString();
            txt_RX.Text = X.ToString();
            txt_RY.Text = Y.ToString();
            txt_RR.Text = R.ToString();
            txt_RMS.Text = RMS.ToString();
            txt_DX.Text = dX.ToString();
            txt_DY.Text = dY.ToString();
            txt_DR.Text = dR.ToString();
            textBox1.Text = "";
            textBox4.Text = "";
        }
        private void ClearDisplay()
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => ClearDisplay()));
                return;
            }
            cogRecordDisplay1.InteractiveGraphics.Clear();
            cogRecordDisplay1.StaticGraphics.Clear();
            cogRecordDisplay1.Image = null;
        }

        private void ImageDisplay(CogGraphicCollection graphics)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => ImageDisplay(graphics)));
                return;
            }
            cogRecordDisplay1.StaticGraphics.AddList(graphics, "");
        }
        private void ImageDisplay(CogImage8Grey img)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => ImageDisplay(img)));
                return;
            }
            cogRecordDisplay1.Image = img;
            cogRecordDisplay1.StaticGraphics.Clear();
        }
        private void ImageDisplayFit()
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => ImageDisplayFit()));
                return;
            }
            cogRecordDisplay1.Fit(true);
        }
        private void DataDisplay(double Rotation, double X, double Y, double Radius)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() => DataDisplay(Rotation, X, Y, Radius)));
                return;
            }
            int rowIndex = dataGridView1.Rows.Add();
            dataGridView1.Rows[rowIndex].Cells["Column1"].Value = Rotation;
            dataGridView1.Rows[rowIndex].Cells["Column2"].Value = X;
            dataGridView1.Rows[rowIndex].Cells["Column3"].Value = Y;
            dataGridView1.Rows[rowIndex].Cells["Column4"].Value = Radius;

        }
        string SavePath;
        private void Save()
        {
            if (!Directory.Exists(SavePath))
            {
                Directory.CreateDirectory(SavePath);
            }
            foreach (var item in Images)
            {
                using (CogImageFile imgFile = new CogImageFile())
                {
                    imgFile.Open(Path.Combine(SavePath, DateTime.Now.ToString("yyyyMMdd_HHmmss_fff") + ".bmp"), CogImageFileModeConstants.Write);
                    imgFile.Append(item);
                }
            }
        }
        private double m_cameraCount = 82;
        private double m_codeCount = 4096;
        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            m_cameraCount = Convert.ToDouble(textBox2.Text);
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            m_codeCount = Convert.ToDouble(textBox3.Text);
        }
        private double m_roateX = 1;
        private double m_roateY = -1;
        private void nud_SizeX_ValueChanged(object sender, EventArgs e)
        {
            m_roateX = Convert.ToDouble(nud_SizeX.Value);
        }

        private void nud_SizeY_ValueChanged(object sender, EventArgs e)
        {
            m_roateY = Convert.ToDouble(nud_SizeY.Value);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (angle > 0)
            {
                double exr = 360 - angle;
                var cir = Rotation2D.RotatePointDegrees(Convert.ToDouble(TCP_X), Convert.ToDouble(TCP_Y), m_roateX, m_roateY, exr, true, false);
                CogGraphicCollection graphics = new CogGraphicCollection();
                AddPointMarker(graphics, cir.x, cir.y, CogColorConstants.Purple);
                cogRecordDisplay1.StaticGraphics.AddList(graphics, "");
                textBox1.Text = cir.x.ToString("F4");
                textBox4.Text = cir.y.ToString("F4"); ;
                if (_s7 != null)
                {

                    _s7.SetValue(arMode, (ushort)0);
                    //_s7.SetValue(arSizeX, Convert.ToSingle(nud_SizeX.Value));
                    //_s7.SetValue(arSizeY, Convert.ToSingle(nud_SizeY.Value));
                    _s7.SetValue(arSizeR, Convert.ToSingle(exr));
                    _s7.SetValue(arAction, true);
                    Thread.Sleep(20);
                    while (true)
                    {
                        bool value = false;
                        if (_s7.GetValue(arOver, out value))
                        {
                            if (value)
                            {
                                _s7.SetValue(arAction, false);
                                break;
                            }
                            else
                            {
                                Thread.Sleep(20);
                                continue;
                            }
                        }
                        else
                        {
                            Thread.Sleep(20);
                            continue;
                        }
                    }
                }
            }
        }
    }
}
