using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace UAS_MES_NEW.PublicMethod
{
    class ModeBusTCPServer
    {
        //M501指令OK,M502指令OK
        //1,2位表示指令类型,读写或者开关,3,4位表示寄存器地址,5,6表示对寄存器的操作,7,8位表示补码,需要计算
        byte[] M501_ON = new byte[] { 0x00, 0x05, 0x11, 0xF5, 0xFF, 0x00, 0x98, 0xE5 };
        byte[] M501_OFF = new byte[] { 0x00, 0x05, 0x11, 0xF5, 0x00, 0x00, 0xD9, 0x15 };
        byte[] M502_ON = new byte[] { 0x00, 0x05, 0x11, 0xF6, 0xFF, 0x00, 0x68, 0xE5 };
        byte[] M502_OFF = new byte[] { 0x00, 0x05, 0x11, 0xF6, 0x00, 0x00, 0x29, 0x15 };
        byte[] M503_READ = new byte[] { 0x00, 0x01, 0x11, 0xF7, 0x00, 0x01, 0x48, 0xD5 };
        byte[] M503_OFF = new byte[] { 0x00, 0x05, 0x11, 0xF7, 0x00, 0x00, 0x78, 0xD5 };
        private bool isOpen = false;

        Thread threadWatch = null; //负责监听客户端的线程
        Socket socketWatch = null; //负责监听客户端的套接字
        Socket socConnection;
        //等待机械臂完成动作
        bool WaitFinish = true;

        public bool IsOpen
        {
            get
            {
                return isOpen;
            }

            set
            {
                isOpen = value;
            }
        }

        public string IP
        {
            get
            {
                return iP;
            }

            set
            {
                iP = value;
            }
        }

        public string Port
        {
            get
            {
                return port;
            }

            set
            {
                port = value;
            }
        }

        private string iP;

        private string port;

        public ModeBusTCPServer()
        {

        }


        public bool Open()
        {
            try
            {
                //定义一个套接字用于监听客户端发来的信息  包含3个参数(IP4寻址协议,流式连接,TCP协议)
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //服务端发送信息 需要1个IP地址和端口号
                IPAddress ipaddress = IPAddress.Parse(iP);
                //将IP地址和端口号绑定到网络节点endpoint上 
                IPEndPoint endpoint = new IPEndPoint(ipaddress, int.Parse(port));
                //监听绑定的网络节点
                socketWatch.Bind(endpoint);
                //将套接字的监听队列长度限制为20
                socketWatch.Listen(20);
                //创建一个监听线程 
                threadWatch = new Thread(WatchConnecting);
                //将窗体线程设置为与后台同步
                threadWatch.IsBackground = true;
                //启动线程
                threadWatch.Start();
                isOpen = true;
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
        }

        private void WatchConnecting()
        {
            socConnection = socketWatch.Accept();
            while (true)  //持续不断监听客户端发来的请求
            {
                byte[] data = new byte[1024];
                socConnection.Receive(data);
                int length = data[5];
                byte[] datashow = new byte[length + 6];
                for (int i = 0; i <= length + 5; i++)
                {
                    datashow[i] = data[i];
                }
                string stringdata = BitConverter.ToString(datashow);//把数组转换成16进制字符串
                stringdata = stringdata.Replace("-", "");
                //503口打开
                if (stringdata.Substring(7, 1) == "1")
                {
                    socConnection.Send(M501_OFF);
                    socConnection.Send(M502_OFF);
                    socConnection.Send(M503_OFF);
                    WaitFinish = false;
                }
            }
        }

        public void Close()
        {
            threadWatch.Abort();
            socketWatch.Close();
            isOpen = false;
        }

        public void SendOrder(string Code)
        {
            switch (Code)
            {
                case "M501_ON":
                    socConnection.Send(M501_ON);
                    WaitFinish = true;
                    int LoopTime = 0;
                    while (WaitFinish && LoopTime <= 40)
                    {
                        Thread.Sleep(100);
                        LoopTime += LoopTime + 1;
                        socConnection.Send(M503_READ);
                    }
                    break;
                case "M501_OFF":
                    socConnection.Send(M501_OFF);
                    break;
                case "M502_ON":
                    socConnection.Send(M502_ON);
                    WaitFinish = true;
                    int LoopTime1 = 0;
                    while (WaitFinish && LoopTime1 <= 40)
                    {
                        Thread.Sleep(100);
                        LoopTime1 += LoopTime1 + 1;
                        socConnection.Send(M503_READ);
                    }
                    break;
                case "M502_OFF":
                    socConnection.Send(M502_OFF);
                    break;
                case "M503_READ":
                    socConnection.Send(M503_READ);
                    break;
                case "M503_OFF":
                    socConnection.Send(M503_OFF);
                    break;
                default:
                    break;
            }
        }
    }
}