using SimensCNC;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static IMCS.Form_Main;

namespace IMCS.Device
{
    class ETH_S7Simens
    {
        static bool IsUp = false;

        static bool AlarmIsUp = false;

         static bool PLCIsUp = false;

        ETH_S7SimensLib eTH_S7SimensLib = new ETH_S7SimensLib();

        ETHSimensAlarmLib eTHSimensAlarmLib = new ETHSimensAlarmLib();

        ETH_S7SimensPLCLib eTH_S7SimensPLCLib = new ETH_S7SimensPLCLib();

        public RunDatasInfo deviceInfo = new RunDatasInfo();

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    System.Threading.Tasks.Task.Run(() => { ReadDeviceDatas(); });//启动同步收集数据线程，同步线程保持长连接

        //    System.Threading.Tasks.Task.Run(() => { ReadPLCAlarmDatas(); });//启动读取PLC报警信息线程，PLC线程保持长连接
        //}
        public ETH_S7Simens(string ip)
        {
            ReadDeviceDatas(ip, "102");

            eTH_S7SimensLib = new ETH_S7SimensLib();

            eTHSimensAlarmLib = new ETHSimensAlarmLib();

            eTH_S7SimensPLCLib = new ETH_S7SimensPLCLib();
        }

        private void Restart()

        { 
            Thread thtmp = new Thread(new ParameterizedThreadStart(run));

            object appName = Application.ExecutablePath;

            Thread.Sleep(2000);

            thtmp.Abort(appName);
            thtmp.Start(appName);

        }

        private void run(Object obj)

        {

            Process ps = new Process();

            ps.StartInfo.FileName = obj.ToString();

            ps.Start();

        }

        /// <summary>
        /// 读取NC报警信息
        /// </summary>
        public void ReadNCAlarmDatas()
        {
            while (true)
            {
                Thread.Sleep(5000);


            }
        }


        /// <summary>
        /// 读取PLC数据，这里只读取PLC报警
        /// </summary>
        public void ReadPLCAlarmDatas(string ip, string port)
        {
            while (true)
            {
                Thread.Sleep(2000);


                if (PLCIsUp == false)
                {
                    PLCIsUp = SimensPLCConnect(ip, port);
                    if (PLCIsUp == false)
                    {
                        YG.Log.Instance.WriteLogAdd("ETH_S7_PLC 链接失败===>>" );
                    }
                    else
                    {
                        YG.Log.Instance.WriteLogAdd("ETH_S7_PLC 链接成功"); 
                    }
                }
                else
                {
                    PLCIsUp = SimensGetPLCData();
                    if (PLCIsUp == false)
                    {
                        YG.Log.Instance.WriteLogAdd("ETH_S7_PLC读取异常，进行重连。。。");
                      

                        PLCIsUp = SimensPLCConnect(ip, port);
                    }

                }
            }
        }

        /// <summary>
        /// 收集NC同步数据
        /// </summary>
        private void ReadDeviceDatas(string ip, string port)
        {
            int count = 0;
            try
            {
                
                while (IsUp == false && count < 10)
                {
                    count++;
                    
                    IsUp = SimensConnect(ip, port);
                    if (IsUp == false)
                    {
                        YG.Log.Instance.WriteLogAdd("TCP通讯故障");
                    }
                    else
                    {
                        YG.Log.Instance.WriteLogAdd("TCP通讯成功");
                    }
                }
 
                if(IsUp == true)
                {
                    IsUp = SimensGetData();
                } 
 
            }
            catch (Exception ex)
            {
                YG.Log.Instance.WriteLogAdd("连接故障===>" + ex.ToString()); 

            }
            finally
            {
                IsUp = SimensConnect(ip, port);

            }
          
        }

        /// <summary>
        /// 建立西门子通讯
        /// </summary>
        /// <param name="itemEqu"></param>
        /// <returns></returns>
        private bool SimensConnect(string ip, string port)
        {
            return eTH_S7SimensLib.ETH_S7SimensConnect(ip, (ushort)Convert.ToInt32(port), 10);
        }

        /// <summary>
        /// 建立西门子报警通讯
        /// </summary>
        /// <param name="itemEqu"></param>
        /// <returns></returns>
        private bool SimensAlarmConnect(string ip, string port)
        {
            return eTHSimensAlarmLib.ETH_S7SimensConnect(ip, (ushort)Convert.ToInt32(port), 10);
        }


        /// <summary>
        /// 建立西门子PLC通讯
        /// </summary>
        /// <param name="itemEqu"></param>
        /// <returns></returns>
        private bool SimensPLCConnect(string ip,string port)
        {
            return eTH_S7SimensPLCLib.ETH_S7SimensConnect(ip, (ushort)Convert.ToInt32(port), 10);
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        bool SimensGetData()
        {
            Thread.Sleep(10);



            try
            {
 
                object result = 0;
                //Thread.Sleep(10);
                //获取系统类型cnc_type 
                //eTH_S7SimensLib.ETH_S7SimensCNCType(ref result);
                //result.ToString();

                //Thread.Sleep(10);
                ////获取唯一标识号cnc_id
                //eTH_S7SimensLib.ETH_S7SimensGetCNCID(ref result);
                //result.ToString();

                //Thread.Sleep(10);
                ////获取操作模式cnc_mode
                //eTH_S7SimensLib.ETH_S7SimensGetModeInfo(ref result);
                // result.ToString();
                //Thread.Sleep(10);
                ////获取运行状态cnc_runstatus
                //eTH_S7SimensLib.ETH_S7SimensGetStateInfo(ref result);
                //deviceInfo.RunStatus = result.ToString();

                //Thread.Sleep(10);
                ////获取程序名cnc_mainproname
                //eTH_S7SimensLib.ETH_S7SimensGetPrgName(ref result);
                //deviceInfo.MainProg = result.ToString();

                //Thread.Sleep(10);
                //获取设定进给速度cnc_setfspeed
                //eTH_S7SimensLib.ETH_S7SimensGetSetFeedSpeed(ref result);
                //deviceInfo.SetFeedSpeed = result.ToString();

                Thread.Sleep(5);
                //获取实际进给速度cnc_actfspeed
                eTH_S7SimensLib.ETH_S7SimensGetActFeedSpeed(ref result);
                deviceInfo.feedRate = result.ToString();

               // Thread.Sleep(5);
                //获取设定主轴速度cnc_setsspeed
                //eTH_S7SimensLib.ETH_S7SimensGetSetSpSpeed(ref result);
                //deviceInfo.SetSpSpeed = result.ToString();

                Thread.Sleep(5);
                //获取主轴实际速度cnc_actsspeed
                eTH_S7SimensLib.ETH_S7SimensGetActSpSpeed(ref result);
                deviceInfo.spindleSpeed = result.ToString(); 

                Thread.Sleep(5);
                //获取主轴倍率cnc_srate
                eTH_S7SimensLib.ETH_S7SimensGetSFeed(ref result);
                deviceInfo.spindleMagnification = result.ToString();

                Thread.Sleep(5);
                //获取主轴负载cnc_srate
                eTH_S7SimensLib.ETH_S7SimensGetLoad(ref result);
                deviceInfo.spindleLoad = result.ToString();

                Thread.Sleep(500);
                //读取报警个数
                try
                {
                    eTH_S7SimensLib.ETH_S7SimensGetAlarmMsgNum(ref result);

                    if (Convert.ToInt16(result) == 0)
                    {
                        //this.BeginInvoke((new Action(() =>
                        //{
                        //    richTextBox3.Text = "";

                        //    richTextBox3.AppendText("无报警 " + "\r\n");
                        //})));
                    }
                    else
                    {
                        for (int i = 1; i <= Convert.ToInt16(result); i++)
                        {
                            AlmInfo almInfo = new AlmInfo();
                            Thread.Sleep(200);
                            byte[] intBuff = BitConverter.GetBytes(i);
                            //读取报警号
                            eTH_S7SimensLib.ETH_S7SimensGetAlarmMsg(intBuff[0], ref result);
                            almInfo.no = i + "";
                            almInfo.msg = result.ToString();
                            //this.BeginInvoke((new Action(() =>
                            //{

                            //    richTextBox3.AppendText("报警号" + "：" + result.ToString() + "\r\n");
                            //})));
                        }

                    }
                }
                catch (Exception ex)
                {
                    YG.Log.Instance.WriteLogAdd("报警接口读取异常===>" + ex.ToString());
                 

                    return false;

                }
                finally
                {

                }

               


 
                return true;

            }
            catch (Exception ex)
            {
                YG.Log.Instance.WriteLogAdd("读取异常===>" + ex.ToString());
          
                return false;
            }
            finally
            {
                 

            }


        }


        bool SimensGetAllarmData()
        {
            //object result = 0;
            //var s= eTHSimensAlarmLib.AlarmMsg(ref result);
            //this.BeginInvoke((new Action(() =>
            //{
            //    richTextBox3.AppendText( result + "\r\n");

            //})));
            return true;
        }

        bool SimensGetPLCData()
        {
            bool s = false;
            // object result = 0;
            for (int i = 0; i < 31; i++)
            {
                Thread.Sleep(10);
                object result = 0;
                s = eTH_S7SimensPLCLib.ETH_S7SimensGetPLCAlarmMsg(i, ref result);
               
            }
            return s;
        }
    }
}
