using Highway.Assemble.common;
using log4net;
using Mesnac.DeviceAdapter;
using Mesnac.DeviceAdapterNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Highway.Assemble.EquipClient
{
    public class EquipClient : IEquipClient
    {
        public static readonly ILog LogInfo = LogManager.GetLogger("RollingLogFileAppender");

        public Action<List<DeviceInfo>> EquipStateAction;

        public Action<int, byte[]> ReadDataAction;

        public Action<int, byte[]> RecSendDataAction;

        public Action<int, int, int> RecGetDataAction;

        public Action<int, byte[]> RecAutoDataAction;

        public List<Equip> equipList;

        public List<Equip> listGroup;

        public List<Sensor> m_SensorInfoList;

        public List<Sensor> m_AntInfoInfoList;

        public List<DeviceInfo> m_DeviceInfoList;

        private BackgroundWorker m_bgwDeviceDetect = new BackgroundWorker();

        private ManualResetEvent StartDetectEvent = new ManualResetEvent(initialState: false);

        private ManualResetEvent ExitEvent = new ManualResetEvent(initialState: false);

        private ManualResetEvent DetectEvent = new ManualResetEvent(initialState: false);

        public List<CombineData> CombineDataList = new List<CombineData>();

        public static AntInfo[] AntList;

        public CombineData CombineData;

        public bool TagInventory;

        /// <summary>
        /// 初始化设备天线信息
        /// </summary>
        private void InitAnt()
        {
            AntList = new AntInfo[m_SensorInfoList.Count];
            for (int i = 0; i < m_SensorInfoList.Count; i++)
            {
                AntInfo a = new AntInfo();
                a.m_iCombineId = Convert.ToInt32(m_SensorInfoList[i].combineid);
                AntList[i] = a;
            }
        }

        /// <summary>
        /// 初始化创建设备实例
        /// </summary>
        public void Init()
        {
            CombineData = new CombineData();
            DeviceInfo pDeviceInfo = null;
            m_DeviceInfoList = new List<DeviceInfo>();
            if (equipList == null)
            {
                LogInfo.Info("设备信息表为空！");
                return;
            }
            for (int i = 0; i < equipList.Count; i++)
            {
                pDeviceInfo = new DeviceInfo();
                pDeviceInfo.m_iDeviceId = Convert.ToUInt16(equipList[i].deviceId);
                pDeviceInfo.m_iConnectMode = Convert.ToByte(equipList[i].connectmode);
                pDeviceInfo.m_strConnectStr = equipList[i].connectstr;
                pDeviceInfo.m_strDeviceType = equipList[i].deviceType;
                pDeviceInfo.m_IDeviceAdapter = CreateDeviceAdapter(pDeviceInfo);
                if (pDeviceInfo.m_IDeviceAdapter == null)
                {
                    LogInfo.Info("创建编号为" + pDeviceInfo.m_iDeviceId + "的设备实例失败");
                }
                m_DeviceInfoList.Add(pDeviceInfo);
            }
            InitAnt();
        }

        /// <summary>
        /// 创建设备动态链接库
        /// </summary>
        /// <param name="pDeviceInfo"></param>
        /// <returns></returns>
        public IDeviceAdapter CreateDeviceAdapter(DeviceInfo pDeviceInfo)
        {
            IDeviceAdapter IAdapter = null;
            try
            {
                string strDllName = "Mesnac.DeviceAdapter." + pDeviceInfo.m_strDeviceType;
                Assembly assembly = Assembly.Load(strDllName);
                string fullName = strDllName + "." + pDeviceInfo.m_strDeviceType + "Adapter";
                return (IDeviceAdapter)assembly.CreateInstance(fullName);
            }
            catch (Exception ex)
            {
                LogInfo.Info("CreateDeviceAdapter异常:" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 设备数据处理函数
        /// </summary>
        public void CreatEquipClient()
        {
            if (equipList == null)
            {
                LogInfo.Info("设备信息表为空！");
                return;
            }
            m_bgwDeviceDetect.DoWork += bgwDeviceDetect_DoWork;
            m_bgwDeviceDetect.RunWorkerAsync(this);
        }
        /// <summary>
        /// 监听设备数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgwDeviceDetect_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker backgroundworker = sender as BackgroundWorker;
            while (true)
            {
                try
                {
                    if (ExitEvent.WaitOne(0, exitContext: false))
                    {
                        e.Cancel = true;
                        LogInfo.Info("设备检测线程正常退出");
                        ExitEvent.Reset();
                        break;
                    }
                    for (int i = 0; i < m_DeviceInfoList.Count; i++)
                    {
                        DeviceInfo item = m_DeviceInfoList[i];
                        IDeviceAdapter pDeviceAdapter = item.m_IDeviceAdapter;
                        Task t = Task.Run(async delegate
                        {
                            if (pDeviceAdapter == null)
                            {
                                item.m_ConnectState = 0;
                            }
                            if (item.m_ConnectState == 0)
                            {
                                if (pDeviceAdapter.Device_Init_Id((CommType)item.m_iConnectMode, item.m_strConnectStr, item.m_iDeviceId))
                                {
                                    if (pDeviceAdapter.Device_Connect())
                                    {
                                        pDeviceAdapter.RecvIdentifyDataEvent -= RecvIdentifyData_Instance;
                                        pDeviceAdapter.RecvIdentifyDataEvent += RecvIdentifyData_Instance;
                                        pDeviceAdapter.RecvIdentifyData_ToMES_Event -= RecvIdentifyDataToMES_Instance;
                                        pDeviceAdapter.RecvIdentifyData_ToMES_Event += RecvIdentifyDataToMES_Instance;
                                        switch (pDeviceAdapter.Device_SendHeartPack())
                                        {
                                            case 1:
                                                item.m_ConnectState = 1;
                                                break;
                                            case 2:
                                                item.m_ConnectState = 2;
                                                break;
                                            default:
                                                item.m_ConnectState = 0;
                                                break;
                                        }
                                    }
                                }
                                else
                                {
                                    item.m_ConnectState = 0;
                                }
                            }
                            else if (item.m_ConnectState == 1)
                            {
                                switch (pDeviceAdapter.Device_SendHeartPack())
                                {
                                    case 1:
                                        item.m_ConnectState = 1;
                                        break;
                                    case 2:
                                        item.m_ConnectState = 2;
                                        break;
                                    default:
                                        item.m_ConnectState = 0;
                                        break;
                                }
                            }
                            else if (item.m_ConnectState == 2)
                            {
                                switch (pDeviceAdapter.Device_SendHeartPack())
                                {
                                    case 1:
                                        item.m_ConnectState = 1;
                                        break;
                                    case 2:
                                        item.m_ConnectState = 2;
                                        item.m_IDeviceAdapter.Device_Destroy();
                                        break;
                                    default:
                                        item.m_ConnectState = 0;
                                        item.m_IDeviceAdapter.Device_Destroy();
                                        break;
                                }

                            }
                            EquipStateAction?.Invoke(m_DeviceInfoList);
                            await Task.Delay(100);
                        });
                    }
                    DetectEvent.Reset();
                    DetectEvent.WaitOne(120000, exitContext: false);
                }
                catch (Exception ex)
                {
                    LogInfo.Info("设备检测线程异常：" + ex.Message);
                    DetectEvent.Reset();
                    DetectEvent.WaitOne(30000, exitContext: false);
                }
            }
        }
        /// <summary>
        /// 监听MES主动读取后数据返回事件
        /// </summary>
        /// <param name="iLen"></param>
        /// <param name="pData"></param>
        /// <param name="Antenna"></param>
        /// <param name="iDeviceId"></param>
        /// <param name="strId"></param>
        /// <param name="sensorType"></param>
        private void RecvIdentifyDataToMES_Instance(ushort iLen, byte[] pData, byte Antenna, ushort iDeviceId, string strId, string sensorType)
        {
            uint iCombineId = 0u;
            try
            {
                iCombineId = GetCombineIdByDeviceIdAndSer(Antenna, iDeviceId, sensorType);
                if (iCombineId != 0)
                {
                    if (iLen > 0)
                    {
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        LogInfo.Info("MES主动读取合并编号[" + iCombineId + "]的第[" + Antenna + "]号传感器，自报数据：" + Encoding.ASCII.GetString(pData, 0, pData.Length) + "，原始数据：" + bytesToHexStr(pData, pData.Length));
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        ReadDataAction?.Invoke(Convert.ToInt32(iCombineId), pData);
                    }
                    else
                    {
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        LogInfo.Info("MES主动读取合并编号[" + iCombineId + "]的第[" + Antenna + "]号传感器自报数据：NoData");
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        ReadDataAction?.Invoke(Convert.ToInt32(iCombineId), null);
                    }
                }
            }
            catch (Exception ex)
            {
                LogInfo.Info("RecvIdentifyDataToMES_Instance:" + ex.ToString());
                ReadDataAction?.Invoke(Convert.ToInt32(iCombineId), null);
            }
        }

        /// <summary>
        /// 根据设备编号获取传感器合并编号
        /// </summary>
        /// <param name="iSensorSer">传感器编号</param>
        /// <param name="iDeviceId">设备编号</param>
        /// <param name="sensorType">传感器类型</param>
        /// <returns></returns>
        private uint GetCombineIdByDeviceIdAndSer(byte iSensorSer, ushort iDeviceId, string sensorType)
        {
            uint iCombineId = 0u;
            for (int i = 0; i < m_SensorInfoList.Count; i++)
            {
                if (iSensorSer == Convert.ToUInt16(m_SensorInfoList[i].sensorser) && iDeviceId == Convert.ToUInt16(m_SensorInfoList[i].deviceId) && sensorType == m_SensorInfoList[i].sensortypeid)
                {
                    iCombineId = Convert.ToUInt32(m_SensorInfoList[i].combineid);
                    break;
                }
            }
            return iCombineId;
        }

        /// <summary>
        /// 监听自动上报后数据返回事件
        /// </summary>
        /// <param name="iLen">数据长度</param>
        /// <param name="pData">数据</param>
        /// <param name="Antenna">天线</param>
        /// <param name="iDeviceId">设备编号</param>
        /// <param name="strId">传感器编号</param>
        /// <param name="sensorType">传感器类型</param>
        public void RecvIdentifyData_Instance(ushort iLen, byte[] pData, byte Antenna, ushort iDeviceId, string strId, string sensorType)
        {
            uint iCombineId = 0u;
            try
            {
                iCombineId = GetCombineIdByDeviceIdAndSer(Antenna, iDeviceId, sensorType);
                if (iCombineId == 0)
                {
                    return;
                }
                if (iLen > 0)
                {
                    if (iLen == 1)
                    {
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        LogInfo.Info("光电自报合并编号[" + iCombineId + "]的第[" + Antenna + "]号传感器，原始数据：" + bytesToHexStr(pData, pData.Length));
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        RecAutoDataAction?.Invoke(Convert.ToInt32(iCombineId), pData);
                        return;
                    }
                    LogInfo.Info("------------------------------------------------------------------------------------------------------");
                    LogInfo.Info("读写器自报合并编号[" + iCombineId + "]的第[" + Antenna + "]号传感器，自报数据：" + Encoding.ASCII.GetString(pData, 0, pData.Length) + "，原始数据：" + bytesToHexStr(pData, pData.Length));
                    LogInfo.Info("------------------------------------------------------------------------------------------------------");
                    AntInfo[] antList = AntList;
                    foreach (AntInfo item in antList)
                    {
                        if (item.m_iCombineId == iCombineId)
                        {
                            item.IsReading = false;
                            item.ReadData = new byte[pData.Length];
                            Array.Copy(pData, 0, item.ReadData, 0, pData.Length);
                            if (item.readType == 2)
                            {
                                ReadDataAction?.Invoke(Convert.ToInt32(iCombineId), pData);
                            }
                            else
                            {
                                RecSendDataAction?.Invoke(Convert.ToInt32(iCombineId), pData);
                            }
                        }
                    }
                }
                else
                {
                    LogInfo.Info("------------------------------------------------------------------------------------------------------");
                    LogInfo.Info("自报合并编号[" + iCombineId + "]的第[" + Antenna + "]号传感器自报数据：NoData");
                    LogInfo.Info("------------------------------------------------------------------------------------------------------");
                    RecSendDataAction?.Invoke(Convert.ToInt32(iCombineId), null);
                }
            }
            catch (Exception ex)
            {
                LogInfo.Info("空间名：" + ex.Source + "；\n方法名：" + ex.TargetSite?.ToString() + "\n故障点：" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + "\n错误提示：" + ex.Message);
                if (iLen == 0)
                {
                    RecAutoDataAction?.Invoke(Convert.ToInt32(iCombineId), null);
                }
            }
        }

        public static string bytesToHexStr(byte[] bytes, int iLen)
        {
            StringBuilder sb = new StringBuilder();
            if (bytes != null)
            {
                for (int i = 0; i < iLen; i++)
                {
                    sb.Append(bytes[i].ToString("X2"));
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 主动读取设备数据函数
        /// </summary>
        /// <param name="num">传感器合并编号</param>
        /// <param name="filterMembank">过滤区</param>
        /// <param name="filterWordPtr">过滤偏移量</param>
        /// <param name="filterWordCnt">过滤数据长度</param>
        /// <param name="filterData">过滤数据</param>
        /// <param name="Membank">数据区</param>
        /// <param name="WordPtr">数据地址偏移量</param>
        /// <param name="WordCnt">数据长度</param>
        public void ReadData(int num, byte filterMembank, ushort filterWordPtr, ushort filterWordCnt, byte[] filterData, byte Membank, ushort WordPtr, ushort WordCnt)
        {
            ushort iReadLen = 0;
            byte[] pReadData = null;
            DeviceInfo pDeviceInfo = null;
            Sensor pSensorInfo = null;
            try
            {
                LogInfo.Info("接收到MES主动读取数据命令，合并编号：" + num);
                pDeviceInfo = GetIDeviceInfoByCombineId(Convert.ToUInt32(num));
                pSensorInfo = GetSensorInfoByCombineId(Convert.ToUInt32(num));
                if (pDeviceInfo.m_IDeviceAdapter != null)
                {
                    if (pDeviceInfo.m_IDeviceAdapter.Device_Read((G2MemBank)filterMembank, filterWordPtr, filterWordCnt, filterData, (G2MemBank)Membank, WordPtr, WordCnt, ref pReadData, Convert.ToByte(pSensorInfo.sensorser), pSensorInfo.ReadCounts) != 0)
                    {
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        LogInfo.Info("MES主动读取数据成功，合并编号：[" + num + "]，读取标签数据：" + Encoding.ASCII.GetString(pReadData, 0, pReadData.Length) + ",原始数据：" + bytesToHexStr(pReadData, pReadData.Length));
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        ReadDataAction?.Invoke(num, pReadData);
                    }
                    else
                    {
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        LogInfo.Info("MES主动读取数据成功，合并编号：[" + num + "]，读取数据:NoData");
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        ReadDataAction?.Invoke(num, null);
                    }
                }
                else
                {
                    LogInfo.Info("MES主动读取失败，合并编号：" + num);
                    ReadDataAction?.Invoke(num, null);
                }
            }
            catch (Exception ex)
            {
                LogInfo.Info("MES主动读取异常:" + ex.ToString());
                ReadDataAction?.Invoke(num, null);
            }
        }

        /// <summary>
        /// 根据设备编号返回设备信息
        /// </summary>
        /// <param name="iDeviceId">设备编号</param>
        /// <returns>设备信息</returns>
        private DeviceInfo GetDeviceInfoByDeviceId(ushort iDeviceId)
        {
            DeviceInfo pDeviceInfo = null;
            for (int i = 0; i < m_DeviceInfoList.Count; i++)
            {
                if (iDeviceId == m_DeviceInfoList[i].m_iDeviceId)
                {
                    return m_DeviceInfoList[i];
                }
            }
            return pDeviceInfo;
        }
        /// <summary>
        /// 根据传感器合并编号获取设备信息
        /// </summary>
        /// <param name="iCombineId">传感器编号</param>
        /// <returns>设备信息</returns>
        private DeviceInfo GetIDeviceInfoByCombineId(uint iCombineId)
        {
            DeviceInfo pDeviceInfo = null;
            for (int i = 0; i < m_SensorInfoList.Count; i++)
            {
                if (iCombineId == Convert.ToUInt32(m_SensorInfoList[i].combineid))
                {
                    pDeviceInfo = GetDeviceInfoByDeviceId(Convert.ToUInt16(m_SensorInfoList[i].deviceId));
                    if (pDeviceInfo != null)
                    {
                        break;
                    }
                }
            }
            return pDeviceInfo;
        }
        /// <summary>
        /// 根据传感器编号返回传感器信息
        /// </summary>
        /// <param name="iCombineId">传感器编号</param>
        /// <returns>传感器信息</returns>
        private Sensor GetSensorInfoByCombineId(uint iCombineId)
        {
            Sensor pSensorInfo = null;
            for (int i = 0; i < m_SensorInfoList.Count; i++)
            {
                if (iCombineId == Convert.ToUInt32(m_SensorInfoList[i].combineid))
                {
                    pSensorInfo = m_SensorInfoList[i];
                    break;
                }
            }
            return pSensorInfo;
        }

        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="num">传感器合并编号</param>
        /// <param name="filterMembank">过滤区</param>
        /// <param name="filterWordPtr">过滤偏移量</param>
        /// <param name="filterWordCnt">过滤数据长度</param>
        /// <param name="filterData">过滤数据</param>
        /// <param name="Membank">数据区</param>
        /// <param name="WordPtr">数据地址偏移量</param>
        /// <param name="WordCnt">数据长度</param>
        /// <param name="pWriteData">写入数据</param>
        /// <param name="Antenna">天线号</param>
        public void WriteData(int num, byte filterMembank, ushort filterWordPtr, ushort filterWordCnt, byte[] filterData, byte Membank, ushort WordPtr, ushort WordCnt, byte[] pWriteData, byte Antenna)
        {
            int iState = 0;
            ushort iWriteLen = 0;
            DeviceInfo pDeviceInfo = null;
            Sensor pSensorInfo = null;
            switch (Membank)
            {
                case 1:
                    if (pWriteData[0] == byte.MaxValue)
                    {
                        iState = 3;
                        LogInfo.Info("方法：WriteData，接收合并编号[" + num + "]的第[" + Antenna + "]路IO，打开报警灯命令");
                    }
                    else
                    {
                        iState = 4;
                        LogInfo.Info("方法：WriteData，接收合并编号[" + num + "]的第[" + Antenna + "]路IO，关闭报警灯命令");
                    }
                    break;
                case 2:
                    iState = 5;
                    LogInfo.Info("方法：WriteData，接收合并编号[" + num + "]的第[" + Antenna + "]路IO，持续打开报警灯后关闭命令");
                    break;
                case 3:
                    iState = 6;
                    LogInfo.Info("方法：WriteData，接收合并编号[" + num + "]的第[" + Antenna + "]路IO，打开报警灯闪亮命令");
                    break;
            }
            pDeviceInfo = GetIDeviceInfoByCombineId(Convert.ToUInt32(num));
            pSensorInfo = GetSensorInfoByCombineId(Convert.ToUInt32(num));
            try
            {
                if (pDeviceInfo.m_IDeviceAdapter != null)
                {
                    iWriteLen = pDeviceInfo.m_IDeviceAdapter.Device_Write((G2MemBank)filterMembank, filterWordPtr, filterWordCnt, filterData, (G2MemBank)Membank, WordPtr, WordCnt, pWriteData, Convert.ToByte(pSensorInfo.sensorser));
                    RecGetDataAction?.Invoke(num, 1, iState);
                    Thread.Sleep(50);
                }
                else
                {
                    LogInfo.Info("写入失败，合并编号：" + num);
                    RecGetDataAction?.Invoke(num, 0, iState);
                }
            }
            catch (Exception ex)
            {
                LogInfo.Info("写入异常:" + ex.ToString());
            }
        }

        /// <summary>
        /// 主动读取EPC发送给客户端
        /// </summary>
        /// <param name="id">传感器合并编号</param>
        public async Task ReadEPC(int id)
        {
            await Task.Run(delegate
            {
                byte[] array = null;
                try
                {
                    LogInfo.Info("合并编号：" + id + ",识别单次标签命令自报");
                    array = GetOneEpcByCombineId(Convert.ToUInt32(id));
                    if (array != null)
                    {
                        LogInfo.Info("-------------------------------------------------------------------------------------------------------------");
                        LogInfo.Info("识别单次标签成功，合并编号[" + id + "]，读取标签数据：" + Encoding.ASCII.GetString(array, 0, array.Length) + "，原始数据：" + bytesToHexStr(array, array.Length));
                        LogInfo.Info("-------------------------------------------------------------------------------------------------------------");
                        ReadDataAction?.Invoke(id, array);
                    }
                    else
                    {
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        LogInfo.Info("识别单次标签成功，合并编号[" + id + "]，读取标签数据：NoData");
                        LogInfo.Info("------------------------------------------------------------------------------------------------------");
                        ReadDataAction?.Invoke(id, null);
                    }
                }
                catch (Exception ex)
                {
                    LogInfo.Info("Deal_IdentifyOneEpc异常:" + ex.ToString());
                    ReadDataAction?.Invoke(id, null);
                }
            });
        }

        /// <summary>
        /// 根据合并编号主动读取EPC返回原始数据
        /// </summary>
        /// <param name="iCombineId">传感器编号</param>
        /// <returns>原始数据</returns>
        private byte[] GetOneEpcByCombineId(uint iCombineId)
        {
            byte[] pReturnResult = null;
            IDeviceAdapter pDeviceAdapter = null;
            byte iEpcLen = 0;
            for (int i = 0; i < m_SensorInfoList.Count; i++)
            {
                if (iCombineId != Convert.ToUInt32(m_SensorInfoList[i].combineid))
                {
                    continue;
                }
                pDeviceAdapter = GetDeviceAdapterByDeviceId(Convert.ToUInt16(m_SensorInfoList[i].deviceId));
                if (pDeviceAdapter != null)
                {
                    iEpcLen = ((!(m_SensorInfoList[i].returnImm == "1")) ? pDeviceAdapter.Device_GetOneIdentifyData(ref pReturnResult, Convert.ToByte(m_SensorInfoList[i].sensorser), Convert.ToUInt16(m_SensorInfoList[i].DelayTime), 1) : pDeviceAdapter.Device_GetOneIdentifyData(ref pReturnResult, Convert.ToByte(m_SensorInfoList[i].sensorser), Convert.ToUInt16(m_SensorInfoList[i].DelayTime), 1));
                    if (iEpcLen > 0)
                    {
                        return pReturnResult;
                    }
                    return null;
                }
            }
            return pReturnResult;
        }

        /// <summary>
        /// 根据设备编号返回设备动态类
        /// </summary>
        /// <param name="iDeviceId"></param>
        /// <returns>设备动态类</returns>
        private IDeviceAdapter GetDeviceAdapterByDeviceId(ushort iDeviceId)
        {
            IDeviceAdapter pDeviceAdapter = null;
            for (int i = 0; i < m_DeviceInfoList.Count; i++)
            {
                if (iDeviceId == m_DeviceInfoList[i].m_iDeviceId)
                {
                    return m_DeviceInfoList[i].m_IDeviceAdapter;
                }
            }
            return pDeviceAdapter;
        }

        public void RecAutoData(Action<int, byte[]> action)
        {
            RecAutoDataAction = action;
        }

        public void RecEquipState(Action<List<DeviceInfo>> action)
        {
            EquipStateAction = action;
        }

        public void RecGetData(Action<int, int, int> action)
        {
            RecGetDataAction = action;
        }

        public void RecSendData(Action<int, byte[]> action)
        {
            RecSendDataAction = action;
        }

        public void RetReadData(Action<int, byte[]> action)
        {
            ReadDataAction = action;
        }

        public void SensorInfo(List<Sensor> sensorList)
        {
            m_SensorInfoList = sensorList;
        }

        public void EquipInfo(List<Equip> equipList)
        {
            this.equipList = equipList;
        }
        /// <summary>
        /// 根据传感器合并编号处理数据
        /// </summary>
        /// <param name="num">传感器合并编号</param>
        private void Deal_Data(int num)
        {
            AntInfo[] antList = AntList;
            foreach (AntInfo item in antList)
            {
                item.ReadData = null;
                if (item.m_iCombineId != num)
                {
                    continue;
                }
                while (item.IsReading)
                {
                    if (item.ReadData != null)
                    {
                        Array.Clear(item.ReadData, 0, item.ReadData.Length);
                        item.ReadData = null;
                        item.IsReading = false;
                        item.readType = 0;
                    }
                    else
                    {
                        Thread.Sleep(10);
                    }
                }
            }
        }

        /// <summary>
        /// 开始连续盘点
        /// </summary>
        /// <param name="num">传感器合并编号</param>
        public void Device_BeginIdentify(int num)
        {
            bool bResult = false;
            DeviceInfo pDeviceInfo = null;
            Sensor pSensorInfo = null;
            pDeviceInfo = GetIDeviceInfoByCombineId(Convert.ToUInt32(num));
            pSensorInfo = GetSensorInfoByCombineId(Convert.ToUInt32(num));
            AntInfo[] antList = AntList;
            foreach (AntInfo item in antList)
            {
                if (item.m_iCombineId == num)
                {
                    if (item.IsReading)
                    {
                        return;
                    }
                    item.IsReading = true;
                    item.readType = 1;
                }
            }
            LogInfo.Info("合并编号：" + num + ",发送连续读取标签命令自报");
            try
            {
                if (pDeviceInfo.m_IDeviceAdapter != null)
                {
                    bResult = pDeviceInfo.m_IDeviceAdapter.Device_BeginIdentify(Convert.ToByte(pSensorInfo.sensorser), Convert.ToInt32(pSensorInfo.timeout), AutoRead: true, num);
                    if (!bResult)
                    {
                        bResult = pDeviceInfo.m_IDeviceAdapter.Device_BeginIdentify(Convert.ToByte(pSensorInfo.sensorser), Convert.ToInt32(pSensorInfo.timeout), AutoRead: true, num);
                        if (!bResult)
                        {
                            bResult = pDeviceInfo.m_IDeviceAdapter.Device_BeginIdentify(Convert.ToByte(pSensorInfo.sensorser), Convert.ToInt32(pSensorInfo.timeout), AutoRead: true, num);
                        }
                    }
                    Thread.Sleep(1);
                    AntInfo[] antList2 = AntList;
                    foreach (AntInfo item2 in antList2)
                    {
                        if (item2.m_iCombineId == num && !Task.Factory.StartNew(delegate
                        {
                            Deal_Data(item2.m_iCombineId);
                        }).Wait(Convert.ToInt32(pSensorInfo.timeout)))
                        {
                            item2.IsReading = false;
                            item2.readType = 0;
                            DealNoData(num, v: true);
                            item2.ReadData = null;
                        }
                    }
                    if (bResult)
                    {
                        LogInfo.Info("发送连续读取指令成功，合并编号：" + num);
                    }
                    else
                    {
                        LogInfo.Info("发送连续读取指令失败，合并编号：" + num);
                    }
                }
                else
                {
                    LogInfo.Info("发送连续读取指令失败，合并编号：" + num);
                }
            }
            catch (Exception ex)
            {
                LogInfo.Info("发送连续读取指令异常:" + ex.ToString());
            }
        }
        /// <summary>
        /// 连续盘点超时处理
        /// </summary>
        /// <param name="num">传感合并编号</param>
        /// <param name="v">触发方式</param>
        private void DealNoData(int num, bool v)
        {
            if (v)
            {
                LogInfo.Info("》》》触发读取时间超时，返回Nodata，合并编号：" + num);
                RecSendDataAction?.Invoke(Convert.ToInt32(num), null);
            }
            else
            {
                LogInfo.Info("》》》MES主动读取时间超时，返回Nodata，合并编号：" + num);
                ReadDataAction?.Invoke(Convert.ToInt32(num), null);
            }
            Device_StopIdentify(num);
            if (!Device_StopIdentify(num))
            {
                Device_StopIdentify(num);
            }
            if (!Device_StopIdentify(num))
            {
                Device_StopIdentify(num);
            }
        }
        /// <summary>
        /// 停止连续盘点
        /// </summary>
        /// <param name="num">传感器合并编号</param>
        /// <returns></returns>
        public bool Device_StopIdentify(int num)
        {
            bool bResult = false;
            DeviceInfo pDeviceInfo = null;
            Sensor pSensorInfo = null;
            pDeviceInfo = GetIDeviceInfoByCombineId(Convert.ToUInt32(num));
            pSensorInfo = GetSensorInfoByCombineId(Convert.ToUInt32(num));
            LogInfo.Info("合并编号：" + num + ",发送停止连续读取标签命令自报");
            try
            {
                if (pDeviceInfo.m_IDeviceAdapter != null)
                {
                    if (pDeviceInfo.m_IDeviceAdapter.Device_StopIdentify(Convert.ToByte(pSensorInfo.sensorser)))
                    {
                        LogInfo.Info("发送停止连续读取指令成功，合并编号：" + num);
                        return true;
                    }
                    LogInfo.Info("发送停止连续读取指令失败，合并编号：" + num);
                    return false;
                }
                LogInfo.Info("发送停止连续读取指令失败，合并编号：" + num);
                return false;
            }
            catch (Exception ex)
            {
                LogInfo.Info("发送停止连续读取指令异常:" + ex.ToString());
                return false;
            }
        }
        /// <summary>
        /// 客户端连续盘点
        /// </summary>
        /// <param name="num">传感器合并编号</param>
        /// <returns></returns>
        public async Task Device_MESBeginIdentify(int num)
        {
            await Task.Run(delegate
            {
                bool flag = false;
                DeviceInfo deviceInfo = null;
                Sensor sensor = null;
                deviceInfo = GetIDeviceInfoByCombineId(Convert.ToUInt32(num));
                sensor = GetSensorInfoByCombineId(Convert.ToUInt32(num));
                LogInfo.Info("合并编号：" + num + ",MES主动发送连续读取标签命令");
                AntInfo[] antList = AntList;
                foreach (AntInfo antInfo in antList)
                {
                    if (antInfo.m_iCombineId == num)
                    {
                        if (antInfo.IsReading)
                        {
                            LogInfo.Info("合并编号：" + num + ",当前正在读取，请等待上一次读取返回！");
                            return;
                        }
                        antInfo.IsReading = true;
                        antInfo.readType = 2;
                    }
                }
                try
                {
                    if (deviceInfo.m_IDeviceAdapter != null)
                    {
                        flag = deviceInfo.m_IDeviceAdapter.Device_BeginIdentify(Convert.ToByte(sensor.sensorser), Convert.ToInt32(sensor.timeout), AutoRead: false, num);
                        AntInfo[] antList2 = AntList;
                        foreach (AntInfo item in antList2)
                        {
                            if (item.m_iCombineId == num && !Task.Factory.StartNew(delegate
                            {
                                Deal_Data(item.m_iCombineId);
                            }).Wait(Convert.ToInt32(sensor.timeout)))
                            {
                                item.IsReading = false;
                                DealNoData(num, v: false);
                                item.ReadData = null;
                            }
                        }
                    }
                    else
                    {
                        LogInfo.Info("MES主动发送连续读取指令失败，合并编号：" + num);
                    }
                }
                catch (Exception ex)
                {
                    LogInfo.Info("MES主动发送连续读取指令异常:" + ex.ToString());
                }
            });
        }
        /// <summary>
        /// 读取单条EPC
        /// </summary>
        /// <param name="id">传感器合并编号</param>
        /// <returns></returns>
        public string ReadEPCData(int id)
        {
            byte[] pEpc = null;
            string m_data = "";
            try
            {
                LogInfo.Info("合并编号：" + id + ",识别单次标签命令");
                pEpc = GetOneEpcByCombineId(Convert.ToUInt32(id));
                if (pEpc != null)
                {
                    LogInfo.Info("-------------------------------------------------------------------------------------------------------------");
                    LogInfo.Info("识别单次标签成功，合并编号[" + id + "]，读取标签数据：" + Encoding.ASCII.GetString(pEpc, 0, pEpc.Length) + "，原始数据：" + bytesToHexStr(pEpc, pEpc.Length));
                    LogInfo.Info("-------------------------------------------------------------------------------------------------------------");
                    m_data = Encoding.ASCII.GetString(pEpc, 0, pEpc.Length);
                    ReadDataAction?.Invoke(id, pEpc);
                }
                else
                {
                    LogInfo.Info("------------------------------------------------------------------------------------------------------");
                    LogInfo.Info("识别单次标签成功，合并编号[" + id + "]，读取标签数据：NoData");
                    LogInfo.Info("------------------------------------------------------------------------------------------------------");
                    ReadDataAction?.Invoke(id, null);
                }
            }
            catch (Exception ex)
            {
                LogInfo.Info("Deal_IdentifyOneEpc异常:" + ex.ToString());
                ReadDataAction?.Invoke(id, null);
            }
            return m_data;
        }
    }

}
