using CatLib;
using Highway.Assemble.common;
using Highway.Assemble.Common;
using Highway.Assemble.EquipClient;
using Highway.Assemble.Sql;
using Highway.Assemble.SqlSugar.serviceImpl;
using Highway.SocketServer;
using HighWayAssemble.Protocol;
using RRQMSocket;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;
using IPHost = TouchSocket.Sockets.IPHost;
using SocketClient = TouchSocket.Sockets.SocketClient;

namespace HighWayAssemble
{
    public class FrmDisplayModel
    {
        int DeleteLogIntervel = 6;
        string RFID_1_1 = "";
        string RFID_1_2 = "";
        string RFID_2_1 = "";
        string RFID_2_2 = "";
        int IsOPCFlag;
        OPCControls.OPCControlsData opc;
        ISql Sql = null;
        //  IConfigInfo configInfo = null;
        ISoftInfo SoftInfo = null;
        public static IAsyncSocketServer SocketServer = null;
        IBoxDB m_BoxDB = null;
        IEquipClient m_EquipClient = null;
        private List<IOInfo> IO_Infolist = new List<IOInfo>();
        private List<IOInfo> IO_OUTfolist = new List<IOInfo>();
        private List<SocketClient> onLineClient;
        private SimpleTcpService tcpService;
        private TcpService m_service;
        List<byte[]> bufferlit = new List<byte[]>();
        private class IOInfo
        {
            public int id;
            public byte[] state;
            public DateTime time;
        }
        public FrmDisplayModel()
        {
            OnRegister();//绑定回调函数
        }
        /// <summary>
        /// 初始化创建服务端
        /// </summary>
        void Init()
        {
            SoftInfo = App.Make<ISoftInfo>();
            SoftInfo.CollectInfo = new Collect();
            // configInfo = App.Make<IConfigInfo>();
            m_BoxDB = App.Make<IBoxDB>();
            GetConfiginfo();
            Sql = App.Make<ISql>(SoftInfo.CollectInfo.sqlstring);
            GetSoftInfo();
            m_EquipClient = App.Make<IEquipClient>();

            var t = Task.Run(async delegate
            {
                await Task.Delay(10);
                CreateTcp();
                //CreatSocketServer();
                InitEquipClient();
                if (IsOPCFlag == 1)
                {
                    LoadOPCInfo();
                }
                FrmDisplayView.LogInfo.Info("创建SockteSvr成功！");
            });
            Task.Run(async delegate
            {
                while (true)
                {//每十分钟将软件状态插入数据库
                    Sql.InsertCollectState(SoftInfo.CollectInfo.collectID, 1);
                    await Task.Delay(1000 * 60 * 10);
                }
            });

            if (SoftInfo.mode == Mode.Triangle)
            {
                Task.Run(async delegate
                {
                    await Task.Delay(1000);
                    //SendHeard();
                });
                //Thread th = new Thread(SendHeard);
                //th.Start();
            }
            //DealProcessReceive();
            DeleteLogFile();
        }

        private Object obj = new object();
        //消息队列 用于独立线程
        private List<MsgInfo> m_Msg2EquipClient = new List<MsgInfo>(1024);
        private List<MsgInfo> Msg2EquipClient
        {
            get
            {
                lock (obj)
                {
                    return m_Msg2EquipClient;
                }
            }
            set
            {
                lock (obj)
                {
                    m_Msg2EquipClient = value;
                }
            }
        }
        private Object obj1 = new object();
        //消息队列 用于独立线程
        private List<MsgInfo> m_MsgInfolist = new List<MsgInfo>(1024);

        /// <summary>
        /// 数据处理服务类
        /// </summary>
        class MsgInfo
        {
            public DateTime datetime;
            public int Length;
            public byte[] data;
            public long time;
            internal SocketClient SocketClient;
        }
        /// <summary>
        /// 创建OPC客户端
        /// </summary>
        private void LoadOPCInfo()
        {
            try
            {
                opc = new OPCControls.OPCControlsData();
                opc.ValuesChangedWithTimeStamp += new OPCControls.OPCControlsData.ValuesChangedWithTimeStampEventHandler(ValuesChangedWithTimeStampEventHandler);
            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.Fatal("初始化OPC异常!空间名：" + ex.Source + "；" + '\n' +
                  "方法名：" + ex.TargetSite + '\n' +
                  "故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' +
                  "错误提示：" + ex.Message);
            }
        }
        /// <summary>
        /// OPC点位监控实现
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="Value"></param>
        /// <param name="Quality"></param>
        /// <param name="TimeStamp"></param>
        private void ValuesChangedWithTimeStampEventHandler(string Tag, object Value, bool Quality, DateTime TimeStamp)
        {
            try
            {
                FrmDisplayView.LogInfo.Info(string.Format("》》》收到OPC点位信号,Tag:{0},消息内容:{1},时间：{2}", Tag, (int)Value, TimeStamp));
                switch (Tag)
                {
                    //胶架已上小车，用该点值变成1触发RFID上面天线读取胶架号；
                    case @"\\172.18.19.21\HMMLZD.No1_IntoStack_RubberOK.Value":
                        if ((int)Value == 1)
                        {
                            var sensorInfo = SoftInfo.SensorList.Find((x) => { return x.combineid == RFID_1_1; });
                            string INput = m_EquipClient.ReadEPCData(int.Parse(sensorInfo.combineid));
                            if (INput != "")
                            {
                                string strTag = string.Format(@"\\172.18.19.21\HMMLZD.No{0}_IntoStack_RFIDMessage.Value", 1);
                                opc.WriteTag(strTag, INput);
                            }
                        }
                        break;
                    //小车已到指定栈道，请求校验定位是否准确，用该点值变成1触发RFID侧面天线读取栈道入口处芯片；
                    case @"\\172.18.19.21\HMMLZD.No1_IntoStack_Request.Value":
                        if ((int)Value == 1)
                        {
                            var sensorInfo = SoftInfo.SensorList.Find((x) => { return x.combineid == RFID_1_2; });
                            string INput = m_EquipClient.ReadEPCData(int.Parse(sensorInfo.combineid));
                            if (INput != "")
                            {
                                string strTag = string.Format(@"\\172.18.19.21\HMMLZD.No{0}_IntoStack_RealStack.Value", 1);
                                opc.WriteTag(strTag, INput);
                            }
                        }
                        break;
                    //胶架已上小车，用该点值变成1触发RFID上面天线读取胶架号；
                    case @"\\172.18.19.21\HMMLZD.No2_IntoStack_RubberOK.Value":
                        if ((int)Value == 1)
                        {
                            var sensorInfo = SoftInfo.SensorList.Find((x) => { return x.combineid == RFID_2_1; });
                            string INput = m_EquipClient.ReadEPCData(int.Parse(sensorInfo.combineid));
                            if (INput != "")
                            {
                                string strTag = string.Format(@"\\172.18.19.21\HMMLZD.No{0}_IntoStack_RFIDMessage.Value", 2);
                                opc.WriteTag(strTag, INput);
                            }
                        }
                        break;
                    //小车已到指定栈道，请求校验定位是否准确，用该点值变成1触发RFID侧面天线读取栈道入口处芯片；
                    case @"\\172.18.19.21\HMMLZD.No2_IntoStack_Request.Value":
                        if ((int)Value == 1)
                        {
                            var sensorInfo = SoftInfo.SensorList.Find((x) => { return x.combineid == RFID_2_2; });
                            string INput = m_EquipClient.ReadEPCData(int.Parse(sensorInfo.combineid));
                            if (INput != "")
                            {
                                string strTag = string.Format(@"\\172.18.19.21\HMMLZD.No{0}_IntoStack_RealStack.Value", 2);
                                opc.WriteTag(strTag, INput);
                            }
                        }
                        break;
                }


            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.Fatal("接收OPC数据异常!空间名：" + ex.Source + "；" + '\n' +
                "方法名：" + ex.TargetSite + '\n' +
                "故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' +
                "错误提示：" + ex.Message);
            }
        }

        /// <summary>
        /// 加载配置文件信息
        /// </summary>
        void GetConfiginfo()
        {
            try
            {
                SoftInfo.CollectInfo.sqlstring = System.Configuration.ConfigurationManager.AppSettings["SqlString"];
                SoftInfo.CollectInfo.collectID = System.Configuration.ConfigurationManager.AppSettings["CollectID"];
                SoftInfo.CollectInfo.UpdateUrl = System.Configuration.ConfigurationManager.AppSettings["UpdateUrl"];
                DeleteLogIntervel = int.Parse(System.Configuration.ConfigurationManager.AppSettings["DeleteLogIntervel"]);
                IsOPCFlag = int.Parse(System.Configuration.ConfigurationManager.AppSettings["IsOPCFlag"]);
                RFID_1_1 = System.Configuration.ConfigurationManager.AppSettings["1_RFID_1"];
                RFID_1_2 = System.Configuration.ConfigurationManager.AppSettings["1_RFID_2"];
                RFID_2_1 = System.Configuration.ConfigurationManager.AppSettings["2_RFID_1"];
                RFID_2_2 = System.Configuration.ConfigurationManager.AppSettings["2_RFID_2"];
                if (string.IsNullOrEmpty(SoftInfo.CollectInfo.collectID))
                {
                    App.TriggerHalt(EventSystem.LoadCollectID);
                }
            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.Fatal("读取配置文件异常!空间名：" + ex.Source + "；" + '\n' +
                            "方法名：" + ex.TargetSite + '\n' +
                            "故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' +
                            "错误提示：" + ex.Message);
            }
        }
        /// <summary>
        /// 设备信息初始化加载
        /// </summary>
        void InitEquipClient()
        {
            //发送设备信息表
            m_EquipClient.EquipInfo(SoftInfo.EquipList);
            //FrmDisplayView.LogInfo.Debug("》》》InitEquipClient:初始化加载设备");
            //发送传感器
            m_EquipClient.SensorInfo(SoftInfo.SensorList);
            m_EquipClient.Init();
            //设备状态回调
            m_EquipClient.RecEquipState(async (state) =>
            {
                App.TriggerHalt(EventSystem.updateEquipListInfo, state);
                for (int i = 0; i < state.Count; i++)
                {                                
                    //add by 2024-08-26 OPC新增设备断线后写入空格
                    if (state[i].m_ConnectState == 2)
                    {
                        if (state[i].m_iDeviceId == 30101)
                        {
                            string strTag1 = string.Format(@"\\172.18.19.21\HMMLZD.No{0}_IntoStack_RFIDMessage.Value", 1);
                            opc.WriteTag(strTag1, "NoRead");
                            string strTag2 = string.Format(@"\\172.18.19.21\HMMLZD.No{0}_IntoStack_RealStack.Value", 1);
                            opc.WriteTag(strTag2, "NoRead");
                        }
                        if (state[i].m_iDeviceId == 30102)
                        {
                            string strTag = string.Format(@"\\172.18.19.21\HMMLZD.No{0}_IntoStack_RFIDMessage.Value", 2);
                            opc.WriteTag(strTag, "NoRead");
                            string strTag2 = string.Format(@"\\172.18.19.21\HMMLZD.No{0}_IntoStack_RealStack.Value", 2);
                            opc.WriteTag(strTag2, "NoRead");
                        }
                    }
                    //Sql.InsertEquipState(state[i].m_iDeviceId.ToString(), state[i].m_ConnectState);
                    await InsertDeviceState(state[i].m_iDeviceId, state[i].m_ConnectState);
                }
            });
            // 返回读取到的数据  125+4 
            m_EquipClient.RetReadData(async (id, data) =>
            {
                if (IsOPCFlag == 1)
                {
                    string info = "";
                    if (data == null)
                    {
                        info = "NoData";
                    }
                    else
                    {
                        info = MsgUtil.bytesToHexStr(data, data.Length);
                    }
                    App.TriggerHalt(EventSystem.updateSensorListInfo, id, info);
                    //Sql.InsertReadData(id.ToString(), info, 0);
                    await InsertRealWorkData(id.ToString(), info, 0);
                }
                else
                {
                    Head head = new Head();
                    head.start = 0x56;
                    short addr = GetMESCallback(id);
                    head.addr = addr;
                    head.mstaseq = 241;
                    head.control = 125 + 4;
                    byte[] dataInfo;
                    string info = "";
                    if (data == null)
                    {
                        if (SoftInfo.mode == Mode.Triangle)
                        {

                            info = "NoData";
                            dataInfo = Encoding.ASCII.GetBytes(info);

                        }
                        else
                        {
                            dataInfo = new byte[0];
                        }
                    }
                    else
                    {
                        dataInfo = data;// dataInfo = Encoding.ASCII.GetBytes(MsgUtil.bytesToHexStr(data, data.Length));//dataInfo = data;
                        info = MsgUtil.bytesToHexStr(data, data.Length);
                    }
                    var num = BitConverter.GetBytes(id);
                    // = Encoding.ASCII.GetBytes(data);
                    head.length = (Int16)(4 + dataInfo.Length);
                    var headbuf = MsgUtil.StructToBytes(head);
                    byte[] sendbuf = new byte[7 + 4 + dataInfo.Length + 3];
                    Array.Copy(headbuf, 0, sendbuf, 0, headbuf.Length);
                    Array.Copy(num, 0, sendbuf, 7, num.Length);
                    Array.Copy(dataInfo, 0, sendbuf, 7 + 4, dataInfo.Length);
                    byte[] Verify = MsgUtil.CalculateVerify(sendbuf, sendbuf.Length - 3);
                    // Message[Message.Length - 2] = Verify;
                    Array.Copy(Verify, 0, sendbuf, sendbuf.Length - 3, 2);
                    sendbuf[sendbuf.Length - 1] = 0x86;
                    App.TriggerHalt(EventSystem.updateSensorListInfo, id, info);
                    var token = SendMessageToClient(addr, sendbuf);
                    FrmDisplayView.LogInfo.Info(string.Format("发送MES主动读取到的数据 MES地址:{0},消息内容:{1} --{2}", addr, MsgUtil.bytesToHexStr(sendbuf, sendbuf.Length), token == null ? "MES断开" : ""));
                    //2022-11-17 添加注释，等待时间10s
                    //Sql.InsertReadData(id.ToString(), info, 0);
                    await InsertRealWorkData(id.ToString(), info, 0);
                }
            });

            //传感器数据回调 主动读取EPC 125+3
            m_EquipClient.RecSendData(async (id, data) =>
            {
                Head head = new Head();
                head.start = 0x56;
                short addr = GetMESCallback(id);
                head.addr = addr;
                head.mstaseq = 241;
                head.control = 125 + 3;
                byte[] dataInfo;
                string info = "";
                if (data == null)
                {
                    if (SoftInfo.mode == Mode.Triangle)
                    {
                        info = "NoData";
                        dataInfo = Encoding.ASCII.GetBytes(info);
                    }
                    else
                    {
                        dataInfo = new byte[0];
                    }
                }
                else
                {
                    dataInfo = data;// dataInfo = Encoding.ASCII.GetBytes(MsgUtil.bytesToHexStr(data, data.Length));//dataInfo = data;
                    info = MsgUtil.bytesToHexStr(data, data.Length);
                }
                var num = BitConverter.GetBytes(id);
                // byte[] dataInfo = Encoding.ASCII.GetBytes(data);
                head.length = (Int16)(4 + dataInfo.Length);
                var headbuf = MsgUtil.StructToBytes(head);
                byte[] sendbuf = new byte[7 + 4 + dataInfo.Length + 3];
                Array.Copy(headbuf, 0, sendbuf, 0, headbuf.Length);
                Array.Copy(num, 0, sendbuf, 7, num.Length);
                Array.Copy(dataInfo, 0, sendbuf, 7 + 4, dataInfo.Length);
                byte[] Verify = MsgUtil.CalculateVerify(sendbuf, sendbuf.Length - 3);
                Array.Copy(Verify, 0, sendbuf, sendbuf.Length - 3, 2);
                sendbuf[sendbuf.Length - 1] = 0x86;
                App.TriggerHalt(EventSystem.updateSensorListInfo, id, info);

                var token = SendMessageToClient(addr, sendbuf);
                FrmDisplayView.LogInfo.Info(string.Format("发送MES触发读取数据 MES地址:{0},消息内容:{1} --{2}", addr, MsgUtil.bytesToHexStr(sendbuf, sendbuf.Length), token == null ? "MES断开" : ""));
                //2022-11-17 添加注释，等待时间10s
                //Sql.InsertReadData(id.ToString(), info, 2);
                await InsertRealWorkData(id.ToString(), info, 2);

            });
            //自报数据回调
            m_EquipClient.RecAutoData(async (id, data) =>
            {
                //if (IsRepeat(id, data)) //判断光电抖动
                //{
                //    return;
                //}
                string info = "";
                byte[] dataInfo;
                if (data == null)
                {
                    if (SoftInfo.mode == Mode.Triangle)
                    {
                        info = "NoData";
                        dataInfo = Encoding.ASCII.GetBytes(info);
                    }
                    else
                    {
                        dataInfo = new byte[0];
                    }
                }
                else
                {
                    dataInfo = data; //Encoding.ASCII.GetBytes(MsgUtil.bytesToHexStr(data, data.Length));//dataInfo = data;
                    info = MsgUtil.bytesToHexStr(data, data.Length);
                }
                App.TriggerHalt(EventSystem.updateSensorListInfo, id, info);

                if (info == "FF")
                {//这里是IO的信息
                    var sensorInfo = SoftInfo.SensorList.Find((x) => { return x.sensorid == id.ToString(); });
                    if (sensorInfo == null)
                    {
                        return;
                    }
                    else
                    {
                        if (sensorInfo.returnImm.Equals("1"))//
                        {
                            //这里默认是IO类型数据
                            if (sensorInfo.DelayTime > 0)//回调延时
                            {
                                var t = Task.Run(async delegate
                                {
                                    await Task.Delay(sensorInfo.DelayTime);
                                    m_EquipClient.ReadEPC(MsgUtil.ParseToInt(sensorInfo.CallCombineID));
                                });
                            }
                            else
                            {
                                m_EquipClient.ReadEPC(MsgUtil.ParseToInt(sensorInfo.CallCombineID));
                            }
                        }
                        else
                        {//获取到回调读写器的信息
                            var sensor = SoftInfo.SensorList.Find((x) => { return x.sensorid == sensorInfo.CallCombineID; });
                            if (sensor == null)
                            {
                                return;
                            }
                            //var t = Task.Run(async delegate
                            //{
                            //    await Task.Delay(1);
                            //    m_EquipClient.Device_BeginIdentify(MsgUtil.ParseToInt(sensorInfo.CallCombineID));//设置读写器连续读
                            //});
                            Thread m_bgwWaitingForData = new Thread(() => m_EquipClient.Device_BeginIdentify(MsgUtil.ParseToInt(sensorInfo.CallCombineID)));
                            m_bgwWaitingForData.IsBackground = true;
                            m_bgwWaitingForData.Start();
                            //m_EquipClient.Device_BeginIdentify(MsgUtil.ParseToInt(sensorInfo.CallCombineID));//设置读写器连续读
                            //Task.Run(async delegate
                            //{
                            //    await Task.Delay(MsgUtil.ParseToInt(sensorInfo.timeout) + 500);
                            //    if (IdentifyReadData != null)
                            //    {
                            //        dataInfo = new byte[IdentifyReadData.Length];
                            //        Array.Copy(IdentifyReadData, 0, dataInfo, 0, IdentifyReadData.Length);
                            //    }
                            //    else
                            //    {
                            //        dataInfo = Encoding.ASCII.GetBytes("NoData");
                            //    }
                            //});
                        }

                    }
                }

                Head head = new Head();
                head.start = 0x56;
                short addr = GetMESCallback(id);
                head.addr = addr;
                head.mstaseq = 241;
                head.control = 125 + 6;

                var num = BitConverter.GetBytes(id);//合并编号
                                                    // byte[] dataInfo = data;// Encoding.ASCII.GetBytes(data);
                var len = dataInfo.Length;
                head.length = (Int16)(4 + dataInfo.Length + (len == 0 ? 0 : 1));//数据长度
                var headbuf = MsgUtil.StructToBytes(head);
                var sendbuf = new byte[7 + 4 + (len == 0 ? 0 : 1) + len + 3];
                Array.Copy(headbuf, 0, sendbuf, 0, headbuf.Length);
                Array.Copy(num, 0, sendbuf, 7, num.Length);
                sendbuf[7 + 4] = (byte)len;
                Array.Copy(dataInfo, 0, sendbuf, 7 + 4 + 1, dataInfo.Length);
                byte[] Verify = MsgUtil.CalculateVerify(sendbuf, sendbuf.Length - 3);
                Array.Copy(Verify, 0, sendbuf, sendbuf.Length - 3, 2);
                sendbuf[sendbuf.Length - 1] = 0x86;
                var token = SendMessageToClient(addr, sendbuf);
                FrmDisplayView.LogInfo.Info(string.Format("发送MES自报数据 MES地址:{0},消息内容:{1} --{2}", addr, MsgUtil.bytesToHexStr(sendbuf, sendbuf.Length), token == false ? "MES断开" : ""));
                //2022-11-17 添加注释，等待时间10s
                //Sql.InsertReadData(id.ToString(), info, 1);
                await InsertRealWorkData(id.ToString(), info, 1);

            });
            /// 写入的数据是否成功反馈
            m_EquipClient.RecGetData(async (id, data, state) =>
            {
                switch (state)
                {
                    case 3:
                        App.TriggerHalt(EventSystem.updateSensorListInfo, id, "常亮");
                        break;
                    case 4:
                        App.TriggerHalt(EventSystem.updateSensorListInfo, id, "熄灭");
                        break;
                    case 5:
                        App.TriggerHalt(EventSystem.updateSensorListInfo, id, "常亮后自动关闭");
                        break;
                    case 6:
                        App.TriggerHalt(EventSystem.updateSensorListInfo, id, "闪亮");
                        break;
                }
                RecWrite recWrite = new RecWrite();
                recWrite.head.start = 0x56;
                recWrite.head.control = 125 + 5;
                recWrite.head.mstaseq = 241;
                short addr = GetMESCallback(id);
                recWrite.head.addr = addr;
                recWrite.num = id;
                recWrite.head.length = 5;
                recWrite.state = (byte)data;
                var sendbuf = MsgUtil.StructToBytes(recWrite);
                byte[] Verify = MsgUtil.CalculateVerify(sendbuf, sendbuf.Length - 3);
                Array.Copy(Verify, 0, sendbuf, sendbuf.Length - 3, 2);
                sendbuf[sendbuf.Length - 1] = 0x86;
                var token = SendMessageToClient(addr, sendbuf);

                FrmDisplayView.LogInfo.Info(string.Format("发送MES 写入的数据{0} MES地址:{1},消息内容:{2} --{3}", data == 1 ? "成功" : "失败", addr, MsgUtil.bytesToHexStr(sendbuf, sendbuf.Length), token == false ? "MES断开" : ""));
                //Sql.InsertReadData(id.ToString(), recWrite.state.ToString(), state);
                await InsertRealWorkData(id.ToString(), recWrite.state.ToString(), state);
            });
            //Baogq add by 2019年12月2日 09:06:38，新加连接线程
            Task.Run(async delegate
            {
                await Task.Delay(100);
                m_EquipClient.CreatEquipClient();
            });
            //Thread th1 = new Thread(m_EquipClient.CreatEquipClient);
            //th1.Start();
        }
        /// <summary>
        /// 设备状态插库
        /// </summary>
        /// <param name="deviceid">设备编号</param>
        /// <param name="devicestate">设备状态</param>
        /// <returns></returns>
        public async Task<int> InsertDeviceState(int deviceid,int devicestate)
        {
            try
            {
                DeviceState device = new DeviceState();
                device.deviceId = deviceid;
                device.deviceState = devicestate;
                device.deviceTime = DateTime.Now;
                return await new BaseServices<DeviceState>().Add(device);
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
        /// <summary>
        /// 设备数据数据插库
        /// </summary>
        /// <param name="CombID">合并编号</param>
        /// <param name="data">标签数据</param>
        /// <param name="type">上传类型</param>
        /// <returns></returns>
        public async Task<bool> InsertRealWorkData(string CombID, string data, int type)
        {
            try
            {
                RealWorkdata realWorkdata = new RealWorkdata();
                realWorkdata.Combineid = CombID.ToString();
                realWorkdata.Data = data;
                realWorkdata.Reportmode = type;
                realWorkdata.Tm = DateTime.Now;
                realWorkdata.Edittime = DateTime.Now;
                realWorkdata.Deleteflag = 0;
                var MaterialTypeList = await new BaseServices<RealWorkdata>().Add(realWorkdata);
                return true;
            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.Fatal("插入数据失败" + ex.ToString());
                return false;
            }
        }
        /// <summary>
        /// 获取汇集软件、适配软件、设备信息数据
        /// </summary>
        public void GetSoftInfo()
        {
            SoftInfo.mesSoftList = Sql.GetMesEquipList(SoftInfo.CollectInfo.collectID);
            SoftInfo.EquipList = Sql.GetEquipList(SoftInfo.CollectInfo.collectID);
            var collectInfo = Sql.GetCollectInfo(SoftInfo.CollectInfo.collectID);
            SoftInfo.CollectInfo.collectName = collectInfo.collectName;
            SoftInfo.CollectInfo.Port = collectInfo.Port;

            if (SoftInfo.EquipList != null && SoftInfo.EquipList.Count > 0)
            {
                if (SoftInfo.SensorList == null)
                {
                    SoftInfo.SensorList = new List<Sensor>();
                }
                for (int i = 0; i < SoftInfo.EquipList.Count; i++)
                {
                    var sensorInfo = Sql.GetSensorList(SoftInfo.EquipList[i].deviceId);
                    if (sensorInfo != null)
                    {
                        SoftInfo.SensorList.AddRange(sensorInfo);
                    }
                }
            }

            InsetData2Box();
            App.Trigger(EventSystem.UpdateViewList, SoftInfo);
        }
        byte[] Heartbuf = new byte[10];
        /// <summary>
        /// 主动发送心跳函数
        /// </summary>
        void SendHeard()
        {
            //#if !DEBUG
            while (true)
            {
                try
                {
                    Heart heart = new Heart();
                    heart.head.start = 0x56;
                    heart.head.addr = 101;
                    heart.head.control = 101;
                    heart.head.length = 0;
                    heart.head.mstaseq = 241;
                    byte[] headbuf = MsgUtil.StructToBytes(heart.head);
                    Array.Copy(headbuf, 0, Heartbuf, 0, headbuf.Length);
                    byte[] Verify = MsgUtil.CalculateVerify(headbuf, headbuf.Length);
                    Array.Copy(Verify, 0, Heartbuf, 7, Verify.Length);
                    Heartbuf[9] = 0x86;
                    var tokens = onLineClient.ToList();
                    if (tokens != null)
                        FrmDisplayView.LogInfo.Error("当前MES连接数：" + tokens.Count);
                    //判断是否有重复的软件编号

                    for (int i = 0; i < tokens.Count; i++)
                    {
                        if (tokens[i].MainSocket != null)
                        {
                            bool isRepeat = onLineClient.GroupBy(x => x.Id).Any(g => g.Count() > 1);
                            if (isRepeat)
                            {
                                //存在重复编号连接，移除第0个
                                var findflag = onLineClient.FindIndex((x) => { return x.Id == tokens[i].Id; });
                                onLineClient.Remove(onLineClient[findflag]);
                                FrmDisplayView.LogInfo.ErrorFormat("存在重复MES软件连接，移除上次MES软件地址：{0}, IP:{1}:{2}, 成功！", onLineClient[findflag].Id, onLineClient[findflag].IP, onLineClient[findflag].Port);

                                //RemoveMesSocketClientbyFlag(tokens[i].Id);
                            }
                            else
                            {
                                tokens[i].SendAsync(Heartbuf, 0, 10);
                                FrmDisplayView.LogInfo.ErrorFormat("已连接MES软件编号：" + tokens[i].Id + ",MES软件地址：{0} ,端口号：{1},发送MES软件心跳报文:{2}", tokens[i].IP, tokens[i].Port, MsgUtil.bytesToHexStr(Heartbuf, Heartbuf.Length));
                            }
                            
                        }
                    }
                }
                //#endif
                catch (Exception ex)
                {
                    FrmDisplayView.LogInfo.FatalFormat("空间名：" + ex.Source + "；" + '\n' +
                                "方法名：" + ex.TargetSite + '\n' +
                                "故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' +
                                "错误提示：" + ex.Message);
                }
                Thread.Sleep(1000 * 5);
            }
        }
        /// <summary>
        /// 加载本地数据库数据
        /// </summary>
        void InsetData2Box()
        {
            var ConfigDB = m_BoxDB.GetAutoBox().Select<Collect>("from Collect");
            var MesSoftDB = m_BoxDB.GetAutoBox().Select<mesSoft>("from MesSoft");
            var EquipDB = m_BoxDB.GetAutoBox().Select<Equip>("from Equip");
            var SensorDB = m_BoxDB.GetAutoBox().Select<Sensor>("from Sensor");
            if (SoftInfo.CollectInfo.Port != 0)
            {
                if (ConfigDB.Count > 0)
                {
                    for (int i = 0; i < ConfigDB.Count; i++)
                    {
                        m_BoxDB.GetAutoBox().Delete("Collect", ConfigDB[i].index);//
                    }
                }
                m_BoxDB.Insert("Collect", SoftInfo.CollectInfo);
            }
            else
            {
                SoftInfo.CollectInfo.collectName = ConfigDB.Count == 0 ? "请设置正确的软件编号" : ConfigDB[0].collectName + "(初始未连接到数据库)";
                SoftInfo.CollectInfo.Port = ConfigDB.Count == 0 ? 6099 : ConfigDB[0].Port;// m_BoxDB.GetAutoBox().Select<mesSoft>("from MesSoft");
            }
            if (SoftInfo.mesSoftList != null && SoftInfo.mesSoftList.Count != 0)
            {
                if (MesSoftDB.Count > 0)
                {
                    for (int i = 0; i < MesSoftDB.Count; i++)
                    {
                        m_BoxDB.GetAutoBox().Delete("MesSoft", MesSoftDB[i].index);//
                    }

                }
                for (int i = 0; i < SoftInfo.mesSoftList.Count; i++)
                {
                    m_BoxDB.Insert("MesSoft", SoftInfo.mesSoftList[i]);
                }
            }
            else
            {//auto.Select<PlayerInfo>("from PlayerInfo Age ==?",15)
                SoftInfo.mesSoftList = MesSoftDB;// m_BoxDB.GetAutoBox().Select<mesSoft>("from MesSoft");
            }
            if (SoftInfo.EquipList != null && SoftInfo.EquipList.Count != 0)
            {
                if (EquipDB.Count > 0)
                {
                    for (int i = 0; i < EquipDB.Count; i++)
                    {
                        m_BoxDB.GetAutoBox().Delete("Equip", EquipDB[i].index);//
                    }
                }

                for (int i = 0; i < SoftInfo.EquipList.Count; i++)
                {
                    m_BoxDB.Insert("Equip", SoftInfo.EquipList[i]);
                }
            }
            else
            {
                SoftInfo.EquipList = EquipDB;
            }
            if (SoftInfo.SensorList != null && SoftInfo.SensorList.Count != 0)
            {
                if (SensorDB.Count > 0)
                {
                    for (int i = 0; i < SensorDB.Count; i++)
                    {
                        m_BoxDB.GetAutoBox().Delete("Sensor", SensorDB[i].index);//
                    }
                }

                for (int i = 0; i < SoftInfo.SensorList.Count; i++)
                {
                    m_BoxDB.Insert("Sensor", SoftInfo.SensorList[i]);
                }
            }
            else
            {
                SoftInfo.SensorList = SensorDB;
            }
        }
        //根据传感器编号 获取MES ID
        /// <summary>
        /// 获取回调MES编号
        /// </summary>
        /// <param name="id">传感器编号</param>
        /// <returns></returns>
        short GetMESCallback(int id)
        {
            var sensorInfo = SoftInfo.SensorList.Find((x) => { return x.sensorid == id.ToString(); });
            if (sensorInfo == null)
            {
                return 0;
            }
            return (short)MsgUtil.ParseToInt(sensorInfo.mesID);
        }
        /// <summary>
        /// 注册插件服务
        /// </summary>
        void OnRegister()
        {
            App.On(EventSystem.GetSqlSvrData, GetSoftInfo);

            App.Listen(EventSystem.UpdateMesListSQL, () =>
            {
                SoftInfo.mesSoftList = Sql.GetMesEquipList(SoftInfo.CollectInfo.collectID);
                return SoftInfo.mesSoftList;
            });
            App.Listen(EventSystem.updateEquipListInfoSQL, () =>
            {
                SoftInfo.EquipList = Sql.GetEquipList(SoftInfo.CollectInfo.collectID);
                return SoftInfo.EquipList;
            });
            App.Listen(EventSystem.updateSensorListInfoSQL, () =>
            {
                SoftInfo.SensorList = Sql.GetSensorList(SoftInfo.CollectInfo.collectID);
                return SoftInfo.SensorList;
            });

            App.On(EventSystem.StartLoad, () =>
            {
                Init();
            });
            App.On(EventSystem.AppClosed, () =>
            {
                Sql.InsertCollectState(SoftInfo.CollectInfo.collectID, 0);
            });
        }

        /// <summary>
        /// 判断该传感器是否已维护
        /// </summary>
        /// <param name="Senor">传感器编号</param>
        /// <returns></returns>
        bool FindSenor(string Senor)
        {
            bool bResult = false;
            try
            {
                for (int i = 0; i < SoftInfo.SensorList.Count; i++)
                {
                    if (Senor == SoftInfo.SensorList[i].sensorid)
                    {
                        bResult = true;
                        break;
                    }
                    else
                    {
                        bResult = false;
                    }
                }
            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.Info(Senor + "传感器编号异常," + ex);
                bResult = false;
            }
            return bResult;
        }
        /// <summary>
        /// 判断读写器是否立即返回
        /// </summary>
        /// <param name="Senor"></param>
        /// <returns></returns>
        bool FindSenorType(string Senor)
        {
            bool bResult = false;
            try
            {
                for (int i = 0; i < SoftInfo.SensorList.Count; i++)
                {
                    if (Senor == SoftInfo.SensorList[i].sensorid)
                    {
                        if (SoftInfo.SensorList[i].returnImm == "1")
                        {
                            bResult = true;
                            break;
                        }
                        else
                        {
                            bResult = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.Info(Senor + "传感器编号异常," + ex);
                bResult = false;
            }
            return bResult;
        }
        /// <summary>
        /// 删除30天前的日志
        /// </summary>
        void DeleteLogFile()
        {
            var t = Task.Run(async delegate
            {
                while (true)
                {
                    if (DateTime.Now.Hour == 6)
                    {
                        //文件夹路径
                        string strFolderPath = Environment.CurrentDirectory + "\\Log\\异常信息日志";
                        DirectoryInfo dyInfo = new DirectoryInfo(strFolderPath);
                        //获取文件夹下所有的文件
                        foreach (FileInfo feInfo in dyInfo.GetFiles())
                        {
                            //判断文件日期是否几天前创建，是则删除
                            if (feInfo.CreationTime < DateTime.Today.AddDays(-1 * 30 * DeleteLogIntervel))
                                feInfo.Delete();
                        }
                        string strFolderPath1 = Environment.CurrentDirectory + "\\Log\\心跳交互日志";
                        DirectoryInfo dyInfo1 = new DirectoryInfo(strFolderPath1);
                        //获取文件夹下所有的文件
                        foreach (FileInfo feInfo1 in dyInfo1.GetFiles())
                        {
                            //判断文件日期是否几天前创建，是则删除
                            if (feInfo1.CreationTime < DateTime.Today.AddDays(-1 * 30 * DeleteLogIntervel))
                                feInfo1.Delete();
                        }
                        string strFolderPath2 = Environment.CurrentDirectory + "\\Log\\设备交互日志";
                        DirectoryInfo dyInfo2 = new DirectoryInfo(strFolderPath2);
                        //获取文件夹下所有的文件
                        foreach (FileInfo feInfo2 in dyInfo2.GetFiles())
                        {
                            //判断文件日期是否几天前创建，是则删除
                            if (feInfo2.CreationTime < DateTime.Today.AddDays(-1 * 30 * DeleteLogIntervel))
                                feInfo2.Delete();
                        }
                        string strFolderPath3 = Environment.CurrentDirectory + "\\Log\\MES交互日志";
                        DirectoryInfo dyInfo3 = new DirectoryInfo(strFolderPath3);
                        //获取文件夹下所有的文件
                        foreach (FileInfo feInfo3 in dyInfo3.GetFiles())
                        {
                            //判断文件日期是否几天前创建，是则删除
                            if (feInfo3.CreationTime < DateTime.Today.AddDays(-1 * 30 * DeleteLogIntervel))
                                feInfo3.Delete();
                        }
                    }
                    await Task.Delay(1000 * 60 * 60);
                }
            });
        }

        /// <summary>
        /// 创建与MES通讯的服务端
        /// </summary>
        private void CreateTcp()
        {
            if (m_service == null)
            {
                onLineClient = new List<SocketClient>();
                m_service = new TcpService();
                m_service.Connected = this.M_service_Connected;//有客户端连接
                m_service.Disconnected = this.M_service_Disconnected;//有客户端断开连接
                //这里应该引入多线程并加锁处理
                m_service.Received += (client, byteBlock, requestInfo) =>
                {

                    //接收信息，在CustomDataHandlingAdapter派生的适配器中，byteBlock将为null，requestInfo将为适配器定义的泛型
                    if (requestInfo is MyRequestInfo myRequestInfo)
                    {

                        FrmDisplayView.LogInfo.Info("》》》接收[" + client.IP + ":" + client.Port + "]客户端原始消息： " + MsgUtil.bytesToHexStr(myRequestInfo.Header, (int)myRequestInfo.Header.Length) + MsgUtil.bytesToHexStr(myRequestInfo.Body, (int)myRequestInfo.Body.Length) + "\r\n");
                        //此处可以处理MyFixedHeaderRequestInfo的相关信息了。
                        ParsingMessages(client, myRequestInfo);

                        string body = Encoding.UTF8.GetString(myRequestInfo.Body, 0, myRequestInfo.Body.Length);
                    }

                };

            }

            m_service.Setup(new TouchSocketConfig()//载入配置     
              .SetListenIPHosts(new IPHost[] { new IPHost("0.0.0.0:" + SoftInfo.CollectInfo.Port) })//同时监听两个地址
                .SetTcpDataHandlingAdapter(() => { return new MyFixedHeaderCustomDataHandlingAdapter(); })//配置适配器
                .SetMaxCount(10000)
                .SetThreadCount(1000)
                .SetCacheTimeoutEnable(false)
                .ConfigureContainer(a =>//容器的配置顺序应该在最前面
                        {

                        })
                .ConfigurePlugins(a =>
                {
                    a.UseCheckClear().SetTick
                    (timeSpan: TimeSpan.FromMinutes(1))
                    .SetCheckClearType(clearType: CheckClearType.OnlyReceive);

                }))
                .Start();//启动
        }

        /// <summary>
        /// 监听MES客户端主动下线事件
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="e"></param>
        private void M_service_Disconnected(TouchSocket.Sockets.SocketClient socket, DisconnectEventArgs e)
        {
            try
            {
                if (e.Manual)
                {
                    FrmDisplayView.LogInfo.ErrorFormat(string.Format("MES无数据交互被动断开 软件地址： {0}，IP：{1}:{2}。 ", socket.Id, socket.IP, socket
.Port));
                }
                else
                {
                    FrmDisplayView.LogInfo.ErrorFormat(string.Format("MES主动断开 软件地址： {0}，IP：{1}:{2}。 ", socket.Id, socket.IP, socket
.Port));
                }
                this.onLineClient.Remove(socket);
                socket.SafeDispose();
                var mesid = SoftInfo.mesSoftList.FindIndex((x) => { return x.mesid == socket.Id.ToString(); });
                if (mesid != -1)
                {
                    //Sql.InsertSoftState(flag.ToString(), 0);
                    SoftInfo.mesSoftList[mesid].State = 0;
                    App.TriggerHalt(EventSystem.UpdateMesListInfo, SoftInfo.mesSoftList);

                }
                //bool iflag = IsHaveMesSocketClientbyIPAndPort(socket.ID.ToString(), socket.IP, socket.Port.ToString());
                //if (iflag)
                //{
                //    this.onLineClient.Remove(socket);
                //    socket.SafeDispose();
                //    var mesid = SoftInfo.mesSoftList.FindIndex((x) => { return x.mesid == socket.ID.ToString(); });
                //    if (mesid != -1)
                //    {
                //        //Sql.InsertSoftState(flag.ToString(), 0);
                //        SoftInfo.mesSoftList[mesid].State = 0;
                //        App.TriggerHalt(EventSystem.UpdateMesListInfo, SoftInfo.mesSoftList);
                //        FrmDisplayView.LogInfo.ErrorFormat(string.Format("MES断开 软件地址： {0}，IP：{1}:{2}。 ", socket.ID, socket.IP, socket
                //            .Port));
                //    }
                //}
            }
            catch (Exception ex)
            {

            }

        }

        /// <summary>
        /// 监听MES客户端主动连接事件
        /// </summary>
        /// <param name="client"></param>
        /// <param name="e"></param>
        private void M_service_Connected(TouchSocket.Sockets.SocketClient client, TouchSocketEventArgs e)
        {
            this.onLineClient.Add(client);
        }

        /// <summary>
        /// 接收MES客户端消息处理函数
        /// </summary>
        /// <param name="client">客户端连接信息</param>
        /// <param name="myRequestInfo">接收消息内容</param>
        private async void ParsingMessages(SocketClient client, MyRequestInfo myRequestInfo)
        {
            byte[] buffer = new byte[myRequestInfo.Header.Length + myRequestInfo.Body.Length];
            Array.Copy(myRequestInfo.Header, 0, buffer, 0, myRequestInfo.Header.Length);
            Array.Copy(myRequestInfo.Body, 0, buffer, myRequestInfo.Header.Length, myRequestInfo.Body.Length);

            byte[] hbt = new byte[7];
            Array.Copy(buffer, 0, hbt, 0, 7);
            Head head = new Head();
            head = (Head)MsgUtil.BytesToStruct(hbt, hbt.Length, head.GetType());
            switch ((RecAppMsgType)head.control)// 找到对应的适配器软件，发送指令给适配器
            {
                case RecAppMsgType._ReadEpc:
                    //LogService.Instance.Info("接收到MES识别EPC数据消息");
                    ReadEPC readEPC = new ReadEPC();
                    readEPC.tail.verifica = new byte[2];
                    readEPC = (ReadEPC)MsgUtil.BytesToStruct(buffer, buffer.Length, readEPC.GetType());

                    await m_EquipClient.ReadEPC(readEPC.num);

                    //LogService.Instance.Debug(string.Format("消息解析成功 识别EPC消息：", readEPC.num));
                    break;
                case RecAppMsgType._ReadData:
                    //  ReadData readData = new ReadData();
                    //LogService.Instance.Info("接收到MES主动读取数据消息");
                    int num = BitConverter.ToInt32(buffer, 7);
                    //if (!FindSenor(num.ToString()))
                    //{
                    //    FrmDisplayView.LogInfo.Info(num.ToString() + "传感器编号异常,不存在此传感器");
                    //    return;
                    //}
                    ushort filterWordPtr = BitConverter.ToUInt16(buffer, 12);//过滤偏移地址
                    ushort len = BitConverter.ToUInt16(buffer, 14);//过滤长度个字节
                    byte[] filterData = new byte[len];//过滤数据
                                                      //  readData.tail.verifica = new byte[2];
                                                      // readData = (ReadData)MsgUtil.BytesToStruct(buffer, buffer.Length, readData.GetType());
                    Array.Copy(buffer, 18, filterData, 0, len);
                    ushort wordPtr = BitConverter.ToUInt16(buffer, 17 + len);
                    ushort WordCnt = BitConverter.ToUInt16(buffer, 19 + len);
                    //m_EquipClient.ReadData(num, buffer[11], filterWordPtr,
                    //    len, filterData, buffer[16 + len], wordPtr, WordCnt);
                    //add by CaesarBao 判断传感器是否立即返回，用于区分单次读还是连续盘点
                    if (FindSenorType(num.ToString()))
                    {
                        await m_EquipClient.ReadEPC(num);
                    }
                    else
                    {
                        await m_EquipClient.Device_MESBeginIdentify(num);     //主动盘点
                    }

                    //Thread m_bgwWaitingForData = new Thread(() => m_EquipClient.Device_MESBeginIdentify(num));
                    //m_bgwWaitingForData.IsBackground = true;
                    //m_bgwWaitingForData.Start();
                    //m_EquipClient.Device_MESBeginIdentify(num);//设置读写器连续读
                    //LogService.Instance.Debug(string.Format("消息解析成功 读取数据消息，编号：{0}", num));
                    break;
                case RecAppMsgType._WirteData:
                    int wirtenum = BitConverter.ToInt32(buffer, 7);
                    //遍历传感器列表，比对传感器编号
                    if (!FindSenor(wirtenum.ToString()))
                    {
                        FrmDisplayView.LogInfo.Info(wirtenum.ToString() + "传感器编号异常,不存在此传感器");
                        return;
                    }
                    ushort wirtefilterWordPtr = BitConverter.ToUInt16(buffer, 12);//过滤偏移地址
                    ushort wirtelen = BitConverter.ToUInt16(buffer, 14);//过滤长度个字节
                    byte[] wirtefilterData = new byte[wirtelen];//过滤数据
                                                                //  readData.tail.verifica = new byte[2];
                                                                // readData = (ReadData)MsgUtil.BytesToStruct(buffer, buffer.Length, readData.GetType());

                    Array.Copy(buffer, 18, wirtefilterData, 0, wirtelen);
                    ushort wirtewordPtr = BitConverter.ToUInt16(buffer, 17 + wirtelen);
                    ushort wirteWordCnt = BitConverter.ToUInt16(buffer, 19 + wirtelen);
                    byte[] wirtedata = new byte[wirteWordCnt];
                    Array.Copy(buffer, 21 + wirtelen, wirtedata, 0, wirteWordCnt);

                    var Sensorinfo = SoftInfo.SensorList.Find((x) => { return x.sensorid == wirtenum.ToString(); });
                    if (!string.IsNullOrEmpty(Sensorinfo.sensorser))
                    {
                        byte antenan = (byte)MsgUtil.ParseToInt(Sensorinfo.sensorser);
                        //FrmDisplayView.LogInfo.Info("向" + wirtenum + "发送报文：" + MsgUtil.bytesToHexStr(buffer, bufferlen));
                        m_EquipClient.WriteData(wirtenum, buffer[11], wirtefilterWordPtr,
                        wirtelen, wirtefilterData, buffer[16 + wirtelen], wirtewordPtr, wirteWordCnt, wirtedata, antenan);
                        //Thread.Sleep(50);
                    }
                    else
                    {
                        FrmDisplayView.LogInfo.Info("传感器天线号异常");
                        return;
                    }
                    //LogService.Instance.Debug(string.Format("写数据消息解析成功"));

                    break;
                case RecAppMsgType._AutoSendData:
                    //////////
                    break;
                #region
                case RecAppMsgType._HeartBeat://心跳不需要处理
                    SignIn(client, buffer, buffer.Length);
                    byte[] addrby = new byte[2];
                    Array.Copy(buffer, 1, addrby, 0, 2);
                    var flag = BitConverter.ToUInt16(addrby, 0);

                    byte[] Heartbuf = new byte[10];
                    Heart heart = new Heart();
                    heart.head.start = 0x56;
                    heart.head.addr = 101;
                    heart.head.control = 101;
                    heart.head.length = 0;
                    heart.head.mstaseq = 241;
                    byte[] headbuf = MsgUtil.StructToBytes(heart.head);
                    Array.Copy(headbuf, 0, Heartbuf, 0, headbuf.Length);
                    byte[] Verify = MsgUtil.CalculateVerify(headbuf, headbuf.Length);
                    Array.Copy(Verify, 0, Heartbuf, 7, Verify.Length);
                    Heartbuf[9] = 0x86;
                    try
                    {
                        var send = SendMessageToClient(flag, Heartbuf);
                        //var token = FrmDisplayModel.SocketServer.SendMessageByFlag(flag, Heartbuf);
                        FrmDisplayView.LogInfo.ErrorFormat("收到MES软件编号：" + flag + ",心跳报文，发送回执:{0}！", MsgUtil.bytesToHexStr(Heartbuf, Heartbuf.Length));
                    }
                    catch (Exception ex)
                    {

                    }


                    break;
                case RecAppMsgType._ReadEquipState://不实现
                    break;
                case RecAppMsgType._SendGetSoftState://不实现
                    break;
                #endregion
                default:
                    break;
            }
            await Task.Delay(1);
        }

        /// <summary>
        /// 向客户端发送消息
        /// </summary>
        /// <param name="flag">客户端编号</param>
        /// <param name="buffer">发送数据</param>
        /// <returns></returns>
        public bool SendMessageToClient(int flag, byte[] buffer)
        {
            try
            {
                if (onLineClient != null)
                {
                    //var index = onLineClient.ToList().FindIndex((x) =>
                    //{
                    //    return x.Id.ToString().Equals(flag.ToString());
                    //});
                    //onLineClient[index].SendAsync(buffer);
                    //修改向所有符合条件的连接发送
                    foreach (var item in onLineClient.Where(x => x.Id.ToString() == flag.ToString()))
                    {
                        item.SendAsync(buffer);
                    }
                    //richTextBox1.AppendText("向编号[" + flag + "]发送消息" + "\r\n");
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.FatalFormat("向编号[" + flag + "]发送:" + MsgUtil.bytesToHexStr(buffer, buffer.Length) + "消息失败，未找到客户端连接！" + ex);
                return false;
            }

        }
        /// <summary>
        /// 接收MES注册消息
        /// </summary>
        /// <param name="client">客户端连接信息</param>
        /// <param name="byteBlock">接收消息内容</param>
        /// <param name="iLength">消息长度</param>
        public void SignIn(SocketClient client, byte[] byteBlock, int iLength)
        {
            try
            {
                byte[] addrby = new byte[2];
                Array.Copy(byteBlock, 1, addrby, 0, 2);
                var flag = BitConverter.ToUInt16(addrby, 0);
                var mesid = SoftInfo.mesSoftList.FindIndex((x) => { return x.mesid == flag.ToString(); });
                FrmDisplayView.LogInfo.ErrorFormat("收到MES软件地址:" + flag + ",IP:" + client.IP + ",端口号:" + client.Port + ",注册解析消息： " + MsgUtil.bytesToHexStr(byteBlock, iLength));
                if (mesid == -1)
                {
                    FrmDisplayView.LogInfo.ErrorFormat("非法连接 ID:{0},IP:{1}", flag.ToString(), client.IP);
                    return;
                }
                else
                {
                    //判断是否已连接
                    if (SoftInfo.mesSoftList[mesid].State != 0)
                    {
                        //判断编号、IP、端口号与已连接的是否一致
                        //这里应该判断IP地址及软件编号
                        if (!IsHaveMesSocketClientbyIPAndPort(flag.ToString(), client.IP, client.Port.ToString()))
                        {
                            //不一致说明客户端更换端口及编号
                            //判断是否已经存在该端口号的连接
                            if (IsHaveMesSocketClientbyPort(client.Port.ToString()))
                            {
                                //更新
                            }
                            //移除符合编号的客户端连接
                            RemoveMesSocketClientbyFlag(flag.ToString());
                        }
                        //else
                        //{
                        //    RemoveMesSocketClientbyFlag(flag.ToString());
                        //}
                    }
                    SoftInfo.mesSoftList[mesid].mesid = flag.ToString();
                    SoftInfo.mesSoftList[mesid].AdatperIP = client.IP;
                    SoftInfo.mesSoftList[mesid].AdapterPort = client.Port.ToString();
                    SoftInfo.mesSoftList[mesid].State = 1;
                    client.ResetId(flag.ToString());
                    App.TriggerHalt(EventSystem.UpdateMesListInfo, SoftInfo.mesSoftList);
                }
                //Sql.InsertSoftState(flag.ToString(), 1);
            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.FatalFormat("空间名：" + ex.Source + "；" + '\n' +
                               "方法名：" + ex.TargetSite + '\n' +
                               "故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' +
                               "错误提示：" + ex.Message);
            }
        }

        /// <summary>
        /// 根据客户端端口号判断是否存在相同客户端连接
        /// </summary>
        /// <param name="port">客户端端口号</param>
        /// <returns></returns>
        public bool IsHaveMesSocketClientbyPort(string port)
        {
            try
            {
                bool iflag = false;
                for (int i = 0; i < onLineClient.ToList().Count; i++)
                {
                    if (onLineClient.ToList()[i].Id != null)
                    {
                        if (onLineClient.ToList()[i].Port.ToString().Equals(port))
                        {
                            iflag = true;
                            var mesid = SoftInfo.mesSoftList.FindIndex((x) => { return x.mesid == onLineClient.ToList()[i].Id.ToString(); });
                            if (mesid != -1)
                            {
                                SoftInfo.mesSoftList[mesid].State = 0;
                                App.TriggerHalt(EventSystem.UpdateMesListInfo, SoftInfo.mesSoftList);
                                //FrmDisplayView.LogInfo.ErrorFormat(string.Format("MES断开 软件地址： {0}，IP：{1}:{2}。 ", socket.Flag, socket.IP, socket
                                //    .Port));
                            }
                            break;
                        }
                    }
                }

                return iflag;
            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.FatalFormat("空间名：" + ex.Source + "；" + '\n' +
                             "方法名：" + ex.TargetSite + '\n' +
                             "故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' +
                             "错误提示：" + ex.Message);
                return false;
            }
        }
        /// <summary>
        /// 根据客户端编号IP端口号判断是否存在相同客户端连接
        /// </summary>
        /// <param name="flag">客户端编号</param>
        /// <param name="IP">客户端IP</param>
        /// <param name="port">客户端端口号</param>
        /// <returns></returns>
        public bool IsHaveMesSocketClientbyIPAndPort(string flag, string IP, string port)
        {
            try
            {
                bool iflag = false;
                if (onLineClient != null && onLineClient.Count > 0)
                {
                    for (int i = 0; i < onLineClient.ToList().Count; i++)
                    {
                        if (onLineClient.ToList()[i].Id != null)
                        {
                            if (onLineClient.ToList()[i].Id.ToString().Equals(flag) && onLineClient.ToList()[i].IP.ToString().Equals(IP) && onLineClient.ToList()[i].Port.ToString().Equals(port))
                            {
                                iflag = true;
                                break;
                            }
                        }
                    }
                }
                return iflag;

            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.FatalFormat("空间名：" + ex.Source + "；" + '\n' +
                             "方法名：" + ex.TargetSite + '\n' +
                             "故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' +
                             "错误提示：" + ex.Message);
                return false;

            }
        }

        /// <summary>
        /// 移除客户端连接信息
        /// </summary>
        /// <param name="Flag">客户端编号</param>
        public void RemoveMesSocketClientbyFlag(string Flag)
        {
            try
            {
                string IP = "";
                string Port = "";
                for (int i = 0; i < onLineClient.ToList().Count; i++)
                {
                    if (onLineClient.ToList()[i].Id != null)
                    {
                        if (onLineClient.ToList()[i].Id.ToString().Equals(Flag))
                        {
                            IP = onLineClient.ToList()[i].IP;
                            Port = onLineClient.ToList()[i].Port.ToString();
                            onLineClient[i].Close();
                            //this.onLineClient.Remove((SocketClient)onLineClient[i]);
                            FrmDisplayView.LogInfo.ErrorFormat("移除上次MES软件地址：{0}, IP:{1}:{2}, 成功！", Flag, IP, Port);

                            //if (this.onLineClient.Remove((SocketClient)onLineClient[i]))
                            //{
                            //    onLineClient[i].Close();
                            //    FrmDisplayView.LogInfo.ErrorFormat("移除上次MES软件地址：{0}, IP:{1}:{2}, 成功！", Flag, IP, Port);

                            //}
                            break;
                        }
                    }
                }

                //var indexof = onLineClient.ToList().FindIndex((x) => { return x.Flag.ToString().Equals(Flag.ToString()); });
                //string IP = onLineClient[indexof].IP;
                //string Port = onLineClient[indexof].Port.ToString();
                //if (this.onLineClient.Remove((SocketClient)onLineClient[indexof]))
                //{
                //    FrmDisplayView.LogInfo.ErrorFormat("移除上次MES软件地址：{0}, IP:{1}:{2}, 成功！", Flag, IP, Port);

                //}
            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.FatalFormat("空间名：" + ex.Source + "；" + '\n' +
                                "方法名：" + ex.TargetSite + '\n' +
                                "故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' +
                                "错误提示：" + ex.Message);

            }
        }
    }
}
