using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SimensCNC
{
    public class ETHSimensAlarmLib
    {
        bool flag=true;
        public static string cncIP;
        int receiveData;

        short alarmMsg =0;

        byte[] sendCommands;

        byte[] buffer;//发送报文容器
        byte[] datas;//接收报文容器

        static IAsyncResult connResult = null;



        public ETHSimensAlarmLib()
        {

        }

        public Socket AlarmSocket { get; set; }

        /// <summary>
        /// 链接函数
        /// </summary>
        public bool ETH_S7SimensConnect(string adrip, ushort port, int overtime)
        {
            cncIP = adrip;
            IPAddress ip = IPAddress.Parse(adrip);
            int ports = Convert.ToInt32(port);
            AlarmSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            connResult = AlarmSocket.BeginConnect(ip, ports, null, null);
            Thread.Sleep(5000);
            connResult.AsyncWaitHandle.WaitOne(5, true);  //等待2秒
            if (connResult.IsCompleted)
            {
                HandShark();

               // ReceiveAlarmData();
                return true;
            }
            else
            {

                return false;
            }
        }

        /// <summary>
        /// 断开设备连接
        /// </summary>
        /// <param name="no">设备编号</param>
        public void ETH_S7SimensDisConnect(string no)
        {
            AlarmSocket.Shutdown(SocketShutdown.Both);
            AlarmSocket.Close();

        }

        /// <summary>
        /// 三次握手
        /// </summary>
        void HandShark()
        {
            AlarmSocket.Send(ETH_S7SimensCommands.FIRST_HAND_SHANK);
            buffer = new byte[1024];
            receiveData = AlarmSocket.Receive(buffer);
            AlarmSocket.Send(ETH_S7SimensCommands.SENCOND_HAND_SHARK);
            buffer = new byte[1024];
            receiveData = AlarmSocket.Receive(buffer);
            AlarmSocket.Send(ETH_S7SimensCommands.THREE_HAND_SHARK);
            buffer = new byte[1024];
            receiveData = AlarmSocket.Receive(buffer);
        }


        public void ReceiveAlarmData()
        {

            //事件监听线程
            Task.Factory.StartNew(new Action(() =>
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 8];
                    try
                    {
                        receiveData = AlarmSocket.Receive(buffer);
                        byte[] datas = new byte[receiveData];
                        //监听到消息
                        if (receiveData > 0)
                        {
                            Array.Copy(buffer, datas, receiveData);

                            if ((datas[3] == 0xc3))//&& (datas[12] == 0x40))
                            {
                                if (datas[187] == 0x01)
                                {
                                    alarmMsg = BitConverter.ToInt16(datas.Skip(39).Take(2).ToArray(), 0);
                                    var sss = String.Format("{0:X2}{0:X2}", datas[54], datas[55]);

                                    flag = true;

                                }
                            }
                            else
                            {
                                flag = false ;
                            }

                        }
                        else
                        {
                            Thread.Sleep(100);
                            flag = false;
                        }
                    }
                    catch
                    { }
                }
            }));
        }


        /// <summary>
        /// 设备报警信息
        /// </summary>
        /// <param name="socket"></param>
        public bool AlarmMsg(ref object result)
        {

            AlarmSocket.Send(ETH_S7SimensCommands.CNC_ALARM);

            Thread.Sleep(10);
            buffer = new byte[1024 * 8];
            receiveData = AlarmSocket.Receive(buffer);

            if (receiveData > 0)
            {
                datas = new byte[receiveData];
                Array.Copy(buffer, datas, receiveData);

                if ((datas[3] == 0xc3))//&& (datas[12] == 0x40))
                {
                    if (datas[187] == 0x01)
                    {
                        var ss = BitConverter.ToInt16(datas.Skip(39).Take(2).ToArray(), 0);
                        var sss = String.Format("{0:X2}{0:X2}", datas[54], datas[55]);

                        result = sss;

                    }
                    return true;
                }
                else
                {
                    return false;
                }




            }
            else
            {
                return false;

            }

          
        }

       
    }

    
}
