using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using Mesnac.Log;
using System.Runtime.InteropServices;
using System.Threading;
using System.Configuration;
using System.Collections;
using System.ComponentModel;

namespace Mesnac.DeviceAdapter.Fuchs
{
    [ClassInterface(ClassInterfaceType.None)]
    public class FuchsAdapter : IDeviceAdapter
    {
        #region 全局变量声明
        //Dictionary<byte, int> dic = new Dictionary<byte, int>();

        public AntInfo[] AntList = AntListInfo.AntList;//0没有读取状态，1主动读，2被动读
        private DeviceType m_iDeviceType = DeviceType.Fuchs;
        ICommunicateService m_ICommunicateService = null;
        public event RecvIdentifyData RecvIdentifyDataEvent = null;
        public event RecvIdentifyData RecvIdentifyData_ToMES_Event = null;  //MES主动读取委托

        private BackgroundWorker m_WaitingDealData = new BackgroundWorker();
        public UInt16 m_iDeviceId = 0;
        private string m_strIp;   //读写器IP或串口号
        private int m_iPort;      //读写器端口号或波特率
        //private readonly string m_ReadTimeout = ConfigurationManager.AppSettings["ReadTimeout"];    //读取失败，重新读取延时时间
        //private readonly string m_ReadCount = ConfigurationManager.AppSettings["ReadCounts"];    //读取失败，重新读取次数
        //private readonly string m_ReadDbm = ConfigurationManager.AppSettings["ReadDbm"];
        //private readonly string m_WriteDbm = ConfigurationManager.AppSettings["WriteDbm"];
        //private readonly string m_AnalysisFlag = ConfigurationManager.AppSettings["AnalysisFlag"]; //1：按照次数最多返回条码；2：按照平均功率最大返回条码
        //private readonly string m_strFilterData = ConfigurationManager.AppSettings["FilterData"]; //过滤数据
        //private readonly string m_strFilterOffset = ConfigurationManager.AppSettings["FilterOffset"]; //过滤偏移，默认为0
        //private readonly string m_strReadOffset = ConfigurationManager.AppSettings["ReadOffset"]; //读取偏移，默认为0
        //private readonly string m_strReadLength = ConfigurationManager.AppSettings["ReadLength"]; //读取偏移，默认为8

        private Mutex mut = new Mutex();

        private bool m_BeginEventSuccessful = false;
        private UInt16 m_IdentifyDataLen = 0;
        private byte[] m_IdentifyData = new byte[19];

        private Semaphore s_BeginEvent = new Semaphore(0, 100000);
        private bool IsUHFAnt = false;
        private Semaphore s_UHFBeginEvent = new Semaphore(0, 100000);//超高频读头
        //private ManualResetEvent BeginEvent = new ManualResetEvent(false);
        private Semaphore m_WaitingForData = new Semaphore(0, 100000);

        public bool TagInventory_Lable = true;//连续盘点标签标志
        //private BackgroundWorker m_bgwWaitingForData = new BackgroundWorker();

        private Semaphore m_GlobalSem = new Semaphore(1, 1);

        private byte m_ReadDataLen = 0;
        private byte[] m_ReadData = null;

        private bool m_bWriteSuccedTag = false;
        private Semaphore m_WriteSem = new Semaphore(0, 100000);

        private bool m_bSetSignleModel = false;
        private Semaphore m_SetSignelModelSem = new Semaphore(0, 100000);

        private bool m_ReadDataSuccessful = false;
        private Semaphore m_ReadSem = new Semaphore(0, 100000);

        private bool m_GetHeartSuccessful = false;
        private Semaphore m_GetHeartSem = new Semaphore(0, 100000);

        private Semaphore m_MulEpcSem = new Semaphore(0, 100000);

        private Semaphore m_StopSem = new Semaphore(0, 100000);
        private bool m_StopIdentifySuccessful = false;

        private Semaphore m_OneEpcSem = new Semaphore(0, 100000);

        private bool m_SetDbmSuccessful = false;
        private Semaphore m_SetDbmSem = new Semaphore(0, 100000);

        private int m_BarcodeGroupCount = 0;
        private byte[] m_MulAllData = null;
        private byte[] m_AutoReadEPC = null;
        private int m_readEPCDataLen = 0;

        private byte m_OneEpcDataLen = 0;
        private byte[] m_OneEpcData = null;

        private byte[] m_filterData = null;
        private byte[] m_CompareData = null;

        private bool bRereadData = false;

        private byte m_OneEpcAntenna = 254;
        #endregion

        public int AutoReport
        {
            get { return AutoReport; }
            set { AutoReport = value; }
        }

        public int Filter
        {
            get { return Filter; }
            set { Filter = value; }
        }

        //private void InitAnt()
        //{
        //    for (int i = 0; i < 8; i++)
        //    {
        //        AntInfo a = new AntInfo();
         //       AntList[i] = a;
        //    }
        //}
        #region 设备连接部分
        public bool Device_Init(CommType iCommType, string pUrl, DeviceType iDeviceType)
        {
            try
            {
                //InitAnt();
                m_iDeviceType = iDeviceType;
                //LogService.Instance.Debug("函数调用:Device_Init Start: ");
                {
                    if (iCommType == CommType.RJ45)  //网口
                    {
                        if (m_ICommunicateService == null)
                        {
                            m_ICommunicateService = new BgTcpClient();
                        }

                        string[] split = pUrl.Split(new Char[] { ':' });
                        m_strIp = split[0];
                        string strTemp = split[1];
                        m_iPort = Convert.ToInt32(strTemp);
                        m_ICommunicateService.Init(m_strIp, m_iPort, this);
                        LogService.Instance.Info("设备初始化成功，IP：" + m_strIp + "端口号:" + m_iPort);
                    }
                    else      //串口,代用串口号和波特率
                    {
                        if (m_ICommunicateService == null)
                        {
                            return false;
                        }

                        string[] split = pUrl.Split(new Char[] { ':' });
                        m_strIp = split[0];
                        string strTemp = split[1];
                        m_iPort = Convert.ToInt32(strTemp);
                        m_ICommunicateService.Init(m_strIp, m_iPort, this);
                        LogService.Instance.Info("设备初始化成功，串口号：" + m_strIp + "波特率:" + m_iPort);
                    }
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("连接读写器异常：" + ex.Message);
                return false;
            }
            return true;
        }

        public bool Device_Init_Id(CommType iCommType, string pUrl, ushort iDeviceId)
        {
            m_iDeviceId = iDeviceId;
            Device_Init(iCommType, pUrl, (DeviceType)1);
            return true;
        }

        public bool Device_Connect()
        {
            try
            {
                if (m_ICommunicateService != null)
                {
                    if (m_ICommunicateService.Connect())
                    {
                        //LogService.Instance.Info("Device_Connect:连接成功");
                        return true;
                    }
                    else
                    {
                        LogService.Instance.Warn("Device_Connect:连接失败");
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("Device_Connect异常：" + ex.Message);
                return false;
            }

        }

        public void Device_Destroy()
        {
            m_ICommunicateService.DisConnect();
        }

        public bool Device_GetState()
        {
            return m_ICommunicateService.GetState();
        }

        public bool Device_ReConnect()
        {
            try
            {
                if (m_ICommunicateService != null)
                {
                    m_ICommunicateService.DisConnect();
                }
            }
            catch { }
            return Device_Connect();
        }
        #endregion
        public void Deal_HFIdentify(byte[] ValidData)
        {
            m_OneEpcData = new byte[12];
            Array.Clear(m_OneEpcData, 0, m_OneEpcData.Length);
            Array.Copy(ValidData, 6, m_OneEpcData, 0, m_OneEpcData.Length);
            Array.Reverse(m_OneEpcData, 0, 4);
            Array.Reverse(m_OneEpcData, 4, 4);
            Array.Reverse(m_OneEpcData, 8, 4);
          
            if (ValidData[3] == 0X32)
            {
                MessageReturn(1);
            }
            else if (ValidData[3] == 0X34)
            {
                MessageReturn(2);
            }
            else if (ValidData[3] == 0X36)
            {
                MessageReturn(3);
            }
            else if (ValidData[3] == 0X38)
            {
                MessageReturn(4);
            }
        }
        public bool Device_DealValidPack(byte[] ValidData)
        {
            //UInt16 iDataLen = 0;
            //LogService.Instance.Debug("----接受的数据："+ StringChange.bytesToHexStr(ValidData, 18) + ",函数调用:Device_DealValidPack 开始!");
            //LogService.Instance.Debug("----函数调用:Device_DealValidPack 开始!" + StringChange.bytesToHexStr(ValidData, 12));
            //LogService.Instance.Debug("Pepperl_Fuchs 进入Device_DealValidPack解析函数");
            try
            {
                //switch (ValidData[2])
                //{
                //    case 0X19:      //高频读头开始连续识别指令
                //        if (ValidData[4] == 0X05)
                //        {
                //            s_BeginEvent.Release();
                //        }
                //        else if(ValidData[4] == 0X00)//高频读头处理数据
                //        {
                //            Deal_HFIdentify(ValidData);
                //        }
                //        else
                //        {
                //            LogService.Instance.Debug("ValidData[2] == 0x00，未知指令\r\n");
                //            return false;
                //        }
                //        break;
                //    case 0X00:      //心跳
                //        if (ValidData[4] == 0x40)
                //        {
                //            Deal_HeartData(ValidData);
                //        }
                //        else
                //        {
                //            LogService.Instance.Debug("ValidData[2] == 0x00，未知指令\r\n");
                //            return false;
                //        }
                //        break;
                //    case 0X02://高频及超高频读头停止连续识别指令
                //        Deal_StopIdentify(ValidData);
                //        break;
                //    case 0X71:      //超高频读头连续读取指令
                //        if (ValidData[4] == 0X05)
                //        {
                //            s_UHFBeginEvent.Release();
                //        }
                //        else if (ValidData[4] == 0X00)
                //        {
                //            Deal_MESIdentify(ValidData);
                //        }
                //        else
                //        {
                //            LogService.Instance.Debug("ValidData[2] == 0x71，未知指令\r\n");
                //            return false;
                //        }
                //        break;
                //    case 0X0A:      //高频及超高频停止连续读取指令
                //        if (ValidData[4] == 0X05)
                //        {
                //            //LogService.Instance.Debug("----函数调用:Device_DealValidPack：NoRead!");
                //            m_ReadDataLen = 0;
                //            m_ReadDataSuccessful = false;
                //            m_ReadSem.Release();
                //        }
                //        else if(ValidData[4] == 0X00)
                //        {
                //            Deal_UHFReadData(ValidData);
                //        }
                //        else
                //        {
                //            LogService.Instance.Debug("ValidData[2] == 0x0A，未知指令\r\n");
                //            return false;
                //        }
                //        break;
                //    case 0X10:  //高频读头单次读标签指令 
                //        if (ValidData[4] == 0X05)
                //        {
                //            m_ReadDataLen = 0;
                //            m_ReadDataSuccessful = false;
                //            m_ReadSem.Release();
                //        }
                //        else if(ValidData[4] == 0X00)
                //        {
                //            Deal_ReadData(ValidData);
                //        }
                //        else
                //        {
                //            LogService.Instance.Debug("ValidData[2] == 0x10，未知指令\r\n");
                //            return false;
                //        }
                //        break;
                //    case 0X05://高频读头NoData
                //        break;
                //    case 0X04://设置读头工作模式高频or超高频
                //        Deal_SetAntCT(ValidData);
                //        break;
                //    case 0X0D:
                //        Deal_UHFWriteData(ValidData);
                //        break;
                //    case 0XBF:
                //        Deal_SetSignelModel(ValidData);
                //        break;
                //    default:
                //        LogService.Instance.Debug("未知指令\r\n");
                //        return false;
                //}
                #region 01.08修改解析函数
                switch (ValidData[4])
                {
                    case 0x40:      //心跳
                        Deal_HeartData(ValidData);
                        break;
                    case 0x05:      //未读到标签&&超高频读头连续识别指令返回 Received:00.06.1D.02.FF.1C.00.06.1D.02.05.1D
                        if (ValidData[1] == 0X06 && ValidData[2] == 0X0A)
                        {
                            //LogService.Instance.Debug("----函数调用:Device_DealValidPack：NoRead!");
                            m_ReadDataLen = 0;
                            m_ReadDataSuccessful = false;
                            m_ReadSem.Release();
                        }
                        else if (ValidData[2] == 0X19) //高频读头发送连续识别指令返回
                        {
                            s_BeginEvent.Release();
                        }
                        else if (ValidData[2] == 0X71)//超高频读头发送连续识别指令返回
                        {
                            s_UHFBeginEvent.Release();
                            LogService.Instance.Info("发送连续识别指令接收返回帧，释放信号量");
                        }
                        else if (ValidData[2] == 0X10)
                        {
                            m_ReadDataLen = 0;
                            m_ReadDataSuccessful = false;
                            m_ReadSem.Release();
                        }
                        //else if (ValidData[0] == 0X00 && ValidData[1] == 0X06 && ValidData[2] == 0X02 && ValidData[3] == 0X02) //停止连续识别返回
                        //{
                        //    m_StopIdentifySuccessful = true;
                        //    m_StopSem.Release();
                        //}
                        break;
                    case 0X04:      //多标签超高频读头接收报文
                        if (ValidData[0] == 0X00 && ValidData[4] == 0X04)
                        {
                            byte bDataLen = 5;
                            m_ReadDataLen = (byte)ValidData[7];
                            //m_OneEpcDataLen = m_ReadDataLen;
                            m_OneEpcDataLen = (byte)(m_ReadDataLen - bDataLen);
                            m_OneEpcData = new byte[m_OneEpcDataLen];
                            Array.Clear(m_OneEpcData, 0, m_OneEpcData.Length);
                            Array.Copy(ValidData, 10, m_OneEpcData, 0, m_OneEpcDataLen);
                            //LogService.Instance.Debug("函数调用:Device_DealValidPack数据解析为：" + Encoding.ASCII.GetString(m_OneEpcData, 0, 9));
                        }
                        else
                        {
                            m_ReadDataLen = 0;
                            m_OneEpcDataLen = 0;
                        }
                        m_ReadSem.Release();
                        break;
                    case 0X02:      //单标签超高频读头
                        if (ValidData[0] == 0X00 && ValidData[4] == 0X02)
                        {
                            //byte bDataLen = 5;
                            m_ReadDataLen = (byte)ValidData[1];
                            //m_OneEpcDataLen = m_ReadDataLen;
                            m_OneEpcDataLen = (byte)(9);
                            m_OneEpcData = new byte[m_OneEpcDataLen];
                            Array.Clear(m_OneEpcData, 0, m_OneEpcData.Length);
                            Array.Copy(ValidData, 8, m_OneEpcData, 0, m_OneEpcDataLen);
                            //LogService.Instance.Debug("函数调用:Device_DealValidPack数据解析为：" + Encoding.ASCII.GetString(m_OneEpcData, 0, 9));
                        }
                        else
                        {
                            m_ReadDataLen = 0;
                            m_OneEpcDataLen = 0;
                        }
                        m_ReadSem.Release();
                        break;
                    case 0X00:      //高频及超高频读头接收报文正常有数据
                        if (ValidData[1] == 0X12 && ValidData[2] == 0X19)
                        {
                            Deal_MESIdentify(ValidData);
                        }
                        else if (ValidData[1] == 0X12 && ValidData[2] == 0X10)
                        {
                            Deal_ReadData(ValidData);
                        }
                        else if (ValidData[1] == 0X14 && ValidData[2] == 0X71) //超高频读头设置按时间段连续盘点后自报数据返回
                        {
                            Deal_MESIdentify(ValidData);
                        }
                        else if (ValidData[1] == 0X14 && ValidData[2] == 0X0A) //超高频读头
                        {
                            Deal_UHFReadData(ValidData);
                        }
                        else if (ValidData[1] == 0X06 && ValidData[2] == 0X04)  //设置读头工作模式返回指令
                        {
                            Deal_SetAntCT(ValidData);
                        }
                        else if (ValidData[2] == 0X0D)
                        {
                            Deal_UHFWriteData(ValidData);
                        }
                        else if (ValidData[1] == 0X06 && ValidData[2] == 0X02)//停止连续识别指令
                        {
                            Deal_StopIdentify(ValidData);
                        }
                        else if (ValidData[2] == 0XBF)
                        {
                            Deal_SetSignelModel(ValidData);
                        }
                        else if (ValidData[2] == 0X01)
                        {
                            Deal_ReadTidData(ValidData);
                        }
                        else
                        {
                            m_ReadDataLen = 0;
                            m_OneEpcDataLen = 0;
                        }
                        break;
                }
                #endregion
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("Device_DealValidPack异常：" + ex.Message);
                return false;
            }
            return true;
        }

        private void Deal_ReadTidData(byte[] ValidData)
        {
            m_ReadDataLen = (byte)ValidData[1];
            //m_OneEpcDataLen = m_ReadDataLen;
            //m_OneEpcDataLen = Convert.ToByte(Convert.ToString(m_ReadDataLen, 16));
            m_OneEpcData = new byte[m_ReadDataLen - 6];
            Array.Clear(m_OneEpcData, 0, m_OneEpcData.Length);
            Array.Copy(ValidData, 6, m_OneEpcData, 0, m_OneEpcData.Length);
            //Array.Reverse(m_OneEpcData, 0, 4);
            //Array.Reverse(m_OneEpcData, 4, 4);
            //Array.Reverse(m_OneEpcData, 8, 4);
            m_ReadDataSuccessful = true;
            m_ReadSem.Release();
        }

        private void Deal_SetSignelModel(byte[] validData)
        {
            m_SetSignelModelSem.Release();
        }

        private void Deal_UHFWriteData(byte[] ValidData)
        {
            m_bWriteSuccedTag = true;
            m_WriteSem.Release();
        }

        private void Deal_SetAntCT(byte[] validData)
        {
            m_SetDbmSuccessful = true;
            m_SetDbmSem.Release();
        }

        private void Deal_StopIdentify(byte[] ValidData)
        {
            if (ValidData[3] == 0X02)
            {
                if (AntList[4].UHFAntenna == true)
                {
                    LogService.Instance.Debug("第5路超高频传感器停止指令接收成功，释放信号量");
                    //dic.Remove(5);
                    AntList[4].m_StopResult.Release();
                }
                else
                {
                    LogService.Instance.Debug("第1路传感器停止指令接收成功，释放信号量");
                    AntList[0].m_StopResult.Release();
                }
            }
            else if (ValidData[3] == 0X04)
            {
                if (AntList[5].UHFAntenna == true)
                {
                    LogService.Instance.Debug("第6路超高频传感器停止指令接收成功，释放信号量");
                    //dic.Remove(6);
                    AntList[5].m_StopResult.Release();
                }
                else
                {
                    LogService.Instance.Debug("第2路传感器停止指令接收成功，释放信号量");
                    AntList[1].m_StopResult.Release();
                }
            }
            else if (ValidData[3] == 0X06)
            {
                if (AntList[6].UHFAntenna == true)
                {
                    LogService.Instance.Debug("第7路超高频传感器停止指令接收成功，释放信号量");
                    //dic.Remove(7);
                    AntList[6].m_StopResult.Release();
                }
                else
                {
                    LogService.Instance.Debug("第3路传感器停止指令接收成功，释放信号量");
                    AntList[2].m_StopResult.Release();
                }
            }
            else if (ValidData[3] == 0X08)
            {
                if (AntList[7].UHFAntenna == true)
                {
                    LogService.Instance.Debug("第8路超高频传感器停止指令接收成功，释放信号量");
                    //dic.Remove(8);
                    AntList[7].m_StopResult.Release();
                }
                else
                {
                    LogService.Instance.Debug("第4路传感器停止指令接收成功，释放信号量");
                    AntList[3].m_StopResult.Release();
                }
            }
        }

        private void Deal_UHFReadData(byte[] ValidData)
        {
            m_ReadDataLen = (byte)ValidData[1];
            m_OneEpcDataLen = (byte)(9);
            m_OneEpcData = new byte[m_OneEpcDataLen];
            Array.Clear(m_OneEpcData, 0, m_OneEpcData.Length);
            Array.Copy(ValidData, 8, m_OneEpcData, 0, m_OneEpcDataLen);
            m_ReadDataSuccessful = true;
            m_ReadSem.Release();
        }

        private void MessageReturn(byte Antenna)
        {
            LogService.Instance.Debug("接收到数据，第"+Antenna+"号传感器类型readType = " + AntList[Antenna - 1].readType);
            if (AntList[Antenna - 1].readType == 2)//MES读
            {
                LogService.Instance.Debug("MES主动读取" + Antenna + "号传感器释放信号量");
                if (RecvIdentifyData_ToMES_Event != null)
                {
                    RecvIdentifyData_ToMES_Event(Convert.ToUInt16(m_OneEpcData.Length), m_OneEpcData, Antenna, m_iDeviceId, m_strIp);
                }
            }
            else /*if (AntList[Antenna - 1].readType == 2)//自动读*/
            {
                LogService.Instance.Debug("自动读取" + Antenna + "号传感器释放信号量");
                if (RecvIdentifyDataEvent != null)
                {
                    RecvIdentifyDataEvent(Convert.ToUInt16(m_OneEpcData.Length), m_OneEpcData, Antenna, m_iDeviceId, m_strIp);
                }
            }
            //AntList[Antenna - 1].IsReading = false;
            LogService.Instance.Debug("天线" + Antenna + " 号 m_WaitResult释放");
            AntList[Antenna - 1].m_WaitResult.Release();
            LogService.Instance.Debug("天线" + Antenna + " 号 m_WaitResult释放2");
        }
        private void Deal_MESIdentify(byte[] ValidData)
        {
            if (ValidData[2] == 0X19)
            {
                //m_ReadDataLen = (byte)ValidData[1];
                //m_OneEpcDataLen = Convert.ToByte(Convert.ToString(m_ReadDataLen, 16));
                m_OneEpcData = new byte[12];
                Array.Clear(m_OneEpcData, 0, m_OneEpcData.Length);
                Array.Copy(ValidData, 6, m_OneEpcData, 0, m_OneEpcData.Length);
                Array.Reverse(m_OneEpcData, 0, 4);
                Array.Reverse(m_OneEpcData, 4, 4);
                Array.Reverse(m_OneEpcData, 8, 4);
                //if (RecvIdentifyData_ToMES_Event != null)
                //{
                //LogService.Instance.Debug("Pepperl_Fuchs 进入Deal_MESIdentify解析函数:" + StringChange.bytesToHexStr(ValidData,18));
                if (ValidData[3] == 0X32)
                {
                    MessageReturn(1);
                }
                else if (ValidData[3] == 0X34)
                {
                    MessageReturn(2);
                }
                else if (ValidData[3] == 0X36)
                {
                    MessageReturn(3);
                }
                else if (ValidData[3] == 0X38)
                {
                    MessageReturn(4);
                }
            }
            else if (ValidData[2] == 0X71)
            {
                s_UHFBeginEvent.Release();
                LogService.Instance.Info("s_UHFBeginEvent释放信号量");
                m_OneEpcDataLen = (byte)9;
                m_OneEpcData = new byte[m_OneEpcDataLen];
                Array.Clear(m_OneEpcData, 0, m_OneEpcData.Length);
                Array.Copy(ValidData, 8, m_OneEpcData, 0, m_OneEpcDataLen);
                //LogService.Instance.Debug("接收自报数据：" + StringChange.bytesToHexStr(m_OneEpcData, m_OneEpcData.Length));

                if (ValidData[3] == 0X02)
                {
                    MessageReturn(5);
                }
                else if (ValidData[3] == 0X04)
                {
                    MessageReturn(6);
                }
                else if (ValidData[3] == 0X06)
                {
                    MessageReturn(7);
                }
                else if (ValidData[3] == 0X08)
                {
                    MessageReturn(8);
                }
            }
            else if (ValidData[2] == 0X10) //高频读头单次读标签
            {
                m_OneEpcData = new byte[12];
                m_ReadDataLen = Convert.ToByte(m_OneEpcData.Length);
                Array.Clear(m_OneEpcData, 0, m_OneEpcData.Length);
                Array.Copy(ValidData, 6, m_OneEpcData, 0, m_OneEpcData.Length);
                //Array.Reverse(m_OneEpcData, 0, 4);
                //Array.Reverse(m_OneEpcData, 4, 4);
                //Array.Reverse(m_OneEpcData, 8, 4);
                m_ReadDataSuccessful = true;
                m_ReadSem.Release();
            }
        }

        private void Deal_ReadData(byte[] ValidData)//处理读取数据返回帧
        {
            m_ReadDataLen = (byte)ValidData[1];
            //m_OneEpcDataLen = m_ReadDataLen;
            m_OneEpcDataLen = Convert.ToByte(Convert.ToString(m_ReadDataLen, 16));
            m_OneEpcData = new byte[m_OneEpcDataLen];
            Array.Clear(m_OneEpcData, 0, m_OneEpcData.Length);
            Array.Copy(ValidData, 6, m_OneEpcData, 0, m_OneEpcDataLen);
            //2020年4月7日 16:30:48  最新修改取消反写标签
            //Array.Reverse(m_OneEpcData, 0, 4);
            //Array.Reverse(m_OneEpcData, 4, 4);
            //Array.Reverse(m_OneEpcData, 8, 4);
            m_ReadDataSuccessful = true;
            m_ReadSem.Release();
        }

        private void Deal_HeartData(byte[] ValidData)//处理心跳返回帧
        {
            try
            {
                if (ValidData[0] == 0X00 && ValidData[4] == 0x40)
                {
                    m_GetHeartSuccessful = true;
                }
                else
                {
                    m_GetHeartSuccessful = false;
                }
            }
            catch (Exception ex)
            {
                m_GetHeartSuccessful = false;
            }
            m_GetHeartSem.Release();
        }

        public UInt16 Device_Read(G2MemBank filterMembank, UInt16 filterWordPtr, UInt16 filterWordCnt, Byte[] filterData,
                G2MemBank Membank, UInt16 WordPtr, UInt16 WordCnt, ref Byte[] pReadData, byte Antenna, int ReadTimes)
        {
            UInt16 resuat = 0;
            int i_ReadCount = 1;
            while (resuat == 0 && ReadTimes > 0)
            {
                //LogService.Instance.Info("读取数据第[" + i_ReadCount + "]次");
                resuat = Device_Read(filterMembank, filterWordPtr, filterWordCnt, filterData, Membank, WordPtr, WordCnt, ref pReadData, Antenna);
                i_ReadCount++;
                ReadTimes--;
            }
            return resuat;
        }

        public UInt16 Device_Read(G2MemBank filterMembank, UInt16 filterWordPtr, UInt16 filterWordCnt, Byte[] filterData,
                        G2MemBank Membank, UInt16 WordPtr, UInt16 WordCnt, ref Byte[] pReadData, byte Antenna)
        {
            byte iResult = 0;
            string s_CompareData1 = "";
            string s_CompareData2 = "";
            try
            {
                //m_GlobalSem.WaitOne(-1, false);
                //LogService.Instance.Info("函数调用:Device_Read 开始:");

                MessagePack pMessagePack = new MessagePack();
                pMessagePack.m_pData = new byte[6];
                Array.Clear(pMessagePack.m_pData, 0, 6);//清空为0
                if (Membank == G2MemBank.EPC)
                {
                    if (Antenna < 5)
                    {
                        pMessagePack.m_pData[0] = 0x00;
                        pMessagePack.m_pData[1] = 0x06;
                        pMessagePack.m_pData[2] = 16;      //读Data区
                                                           //1、2、3、4天线为高频读头
                        pMessagePack.m_pData[3] = (byte)(0X30 + (Antenna * 2));
                        pMessagePack.m_pData[4] = 0x00;
                        pMessagePack.m_pData[5] = 0x00;
                    }
                    //5、6、7、8天线为超高频读头
                    if (Antenna == 5)
                    {
                        pMessagePack.m_pData = new byte[4];
                        Array.Clear(pMessagePack.m_pData, 0, 4);//清空为0
                        pMessagePack.m_pData[0] = 0x00;
                        pMessagePack.m_pData[1] = 0x04;
                        pMessagePack.m_pData[2] = 0x0A;
                        pMessagePack.m_pData[3] = 0x02;
                    }
                    else if (Antenna == 6)
                    {
                        pMessagePack.m_pData = new byte[4];
                        Array.Clear(pMessagePack.m_pData, 0, 4);//清空为0
                        pMessagePack.m_pData[0] = 0x00;
                        pMessagePack.m_pData[1] = 0x04;
                        pMessagePack.m_pData[2] = 0x0A;
                        pMessagePack.m_pData[3] = 0x04;
                    }
                    else if (Antenna == 7)
                    {
                        pMessagePack.m_pData = new byte[4];
                        Array.Clear(pMessagePack.m_pData, 0, 4);//清空为0
                        pMessagePack.m_pData[0] = 0x00;
                        pMessagePack.m_pData[1] = 0x04;
                        pMessagePack.m_pData[2] = 0x0A;
                        pMessagePack.m_pData[3] = 0x06;
                    }
                    else if (Antenna == 8)
                    {
                        pMessagePack.m_pData = new byte[4];
                        Array.Clear(pMessagePack.m_pData, 0, 4);//清空为0
                        pMessagePack.m_pData[0] = 0x00;
                        pMessagePack.m_pData[1] = 0x04;
                        pMessagePack.m_pData[2] = 0x0A;
                        pMessagePack.m_pData[3] = 0x08;
                    }
                }
                else if (Membank == G2MemBank.TID)
                {
                    pMessagePack.m_pData = new byte[4];
                    Array.Clear(pMessagePack.m_pData, 0, 4);//清空为0
                    pMessagePack.m_pData[0] = 0x00;
                    pMessagePack.m_pData[1] = 0x04;
                    pMessagePack.m_pData[2] = 0x01;
                    if (Antenna < 5)
                    {
                        pMessagePack.m_pData[3] = (byte)(0x00 + (Antenna * 2));
                    }

                }
                //m_filterData = new byte[filterWordCnt];
                //m_CompareData = new byte[filterWordCnt];
                //if (filterWordCnt > 0)
                //{
                //    Array.Copy(filterData, 0, m_filterData, 0, filterWordCnt);
                //}
                //Array.Copy(m_filterData, filterWordPtr, m_CompareData, 0, filterWordCnt);
                //m_ReadSem.Release(1);
                m_ReadSem.WaitOne(1, false);
                m_ReadDataLen = 0;
                if (m_ICommunicateService.SendMessage(pMessagePack))   //发送报文成功
                {
                    if (m_ReadSem.WaitOne(2000, false))   //等待结果,并取结果返回。
                    {
                        //if (m_ReadDataLen > 0) //有数据，正常
                        if (m_ReadDataLen > 0)
                        {
                            if (Membank == G2MemBank.TID)
                            {
                                pReadData = new byte[m_OneEpcData.Length];
                                Array.Copy(m_OneEpcData, 0, pReadData, 0, m_OneEpcData.Length);
                                iResult = (byte)(pReadData.Length);
                                m_ReadDataLen = 0;
                            }
                            else
                            {
                                pReadData = new byte[WordCnt];
                                Array.Copy(m_OneEpcData, WordPtr, pReadData, 0, WordCnt);
                                iResult = (byte)(pReadData.Length);
                                m_ReadDataLen = 0;
                            }
                            //Array.Copy(m_OneEpcData, filterWordPtr, m_CompareData, 0, filterWordCnt);
                            //s_CompareData1 = StringChange.bytesToHexStr(m_filterData, m_filterData.Length);
                            //s_CompareData2 = StringChange.bytesToHexStr(m_CompareData, filterWordCnt);
                            //if (s_CompareData1 == s_CompareData2 && Membank == G2MemBank.EPC && filterMembank == G2MemBank.EPC)
                            //{
                            //    pReadData = new byte[WordCnt];
                            //    Array.Copy(m_OneEpcData, WordPtr, pReadData, 0, WordCnt);
                            //    iResult = (byte)(pReadData.Length);
                            //    //LogService.Instance.Info("------------------------------------------------------------------------------------------------------" + "\r\n");
                            //    //LogService.Instance.Info("读取到标签数据为:" + Encoding.ASCII.GetString(pReadData, 0, pReadData.Length) + ",原始数据为: " + StringChange.bytesToHexStr(pReadData, pReadData.Length) + "，数据长度为: " + pReadData.Length + "\r\n");
                            //    //LogService.Instance.Info("------------------------------------------------------------------------------------------------------");
                            //    m_ReadDataLen = 0;
                            //}
                            //else
                            //{
                            //    iResult = 0;
                            //    m_ReadDataLen = 0;
                            //    LogService.Instance.Warn("读取标签数据失败，与过滤标签不符！");
                            //}
                        }
                        else
                        {
                            iResult = 0;
                            m_ReadDataLen = 0;
                            LogService.Instance.Warn("读取标签数据失败,返回数据长度为0");
                        }
                    }
                    else   //超时
                    {
                        m_ReadDataLen = 0;
                        iResult = 0;
                        LogService.Instance.Error("读取标签数据失败,超时未返回");
                    }
                }
                else
                {
                    LogService.Instance.Error("发送读取标签数据命令失败");
                    iResult = 0;
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("读取标签数据异常：" + ex.Message);
                iResult = 0;
            }
            //finally
            //{
            //    m_GlobalSem.Release();
            //}
            return iResult;
        }
        public byte Device_SendHeartPack()
        {
            byte iResult = 0;
            try
            {
                //LogService.Instance.Debug("函数调用:Device_SendHeartPack");
                //m_GlobalSem.WaitOne(-1, false);
                MessagePack pMessagePack = new MessagePack();
                pMessagePack.m_pData = new byte[6];
                Array.Clear(pMessagePack.m_pData, 0, 6);//清空为0
                //发送读取参数QV指令 00 0A BE 02 00 55 51 56 00 00 只适用于一号天线               
                //pMessagePack.m_pData[0] = 0x00;
                //pMessagePack.m_pData[1] = 0x0A;
                //pMessagePack.m_pData[2] = 0xBE;
                //pMessagePack.m_pData[3] = 0x02;
                //pMessagePack.m_pData[4] = 0x00;
                //pMessagePack.m_pData[5] = 0x55;
                //pMessagePack.m_pData[6] = 0x51;
                //pMessagePack.m_pData[7] = 0x56;
                //pMessagePack.m_pData[8] = 0x00;
                //pMessagePack.m_pData[9] = 0x00;

                //baogq add 2019年6月21日 13:38:53
                //心跳指令：00 06 0A 2A 00 00
                //返回：00 06 0A 2A FF 09 00 06 0A 0A 04 0A 
                pMessagePack.m_pData[0] = 0x00;
                pMessagePack.m_pData[1] = 0x16;
                pMessagePack.m_pData[2] = 10;
                pMessagePack.m_pData[3] = 42;
                pMessagePack.m_pData[4] = 0x00;
                pMessagePack.m_pData[5] = 0x00;

                m_GetHeartSem.WaitOne(1, false);
                //m_GetHeartSuccessful = false;
                if (m_ICommunicateService != null)
                {
                    if (m_ICommunicateService.SendMessage(pMessagePack))   //发送报文成功
                    {
                        if (m_GetHeartSem.WaitOne(2000, false))   //等待结果,并取结果返回。
                        {
                            //LogService.Instance.Info("发送心跳报正常。");
                            iResult = 1;        //通讯连接和读写器都正常
                        }
                        else                    //超时
                        {
                            //LogService.Instance.Info("发送心跳报文超时。");
                            iResult = 2;       //通讯连接器正常，读写器故障
                            //Device_Destroy();
                        };
                    }
                    else
                    {
                        //通讯连接器失败或网络故障
                        LogService.Instance.Info("发送心跳报文失败，通讯故障。");
                        iResult = 3;
                        //Device_Destroy();
                    }
                }
                else
                {
                    return 3;
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("Device_SendHeartPack：" + ex.Message);
                iResult = 3;
            }
            //finally
            //{
            //    m_GlobalSem.Release();
            //}
            m_GetHeartSuccessful = false;
            return iResult;
        }

        public Byte Device_GetOneIdentifyData(ref Byte[] pReadData, Byte Antenna, UInt16 Timedout, int ReadCounts)
        {
            byte iResult = 0;
            #region
            /************************************************************************************
             *      Description: 过滤标签形式，可在配置文件配置过滤标签信息
             *		
             *      Author:
             *				鲍国强
             *				Email：baogq@mesnac.com  
             *      Finish DateTime:
             *				2019年6月19日 11:24:39
             *      History:
             ***********************************************************************************/
            #endregion
            //string strFilterData = m_strFilterData.Trim();//过滤数据去空白字符
            //UInt16 iFilterDataLength = Convert.ToUInt16(strFilterData.Length / 2);//过滤长度
            //UInt16 filterOffset = Convert.ToUInt16(m_strFilterOffset.Trim());  //过滤偏移
            //byte[] pFilterData = new byte[iFilterDataLength];
            //for (int i = 0; i < iFilterDataLength; i++)
            //{
            //    pFilterData[i] = Convert.ToByte(strFilterData.Substring(i * 2, 2), 16); //过滤数据
            //}
            //UInt16 readOffset = Convert.ToUInt16(m_strReadOffset.Trim());  //读取偏移
            //UInt16 readLength = Convert.ToUInt16(m_strReadLength.Trim());  //读取长度
            UInt16 iFilterDataLength = 0;
            UInt16 filterOffset = 0;
            byte[] pFilterData = new byte[1];
            UInt16 readOffset = 0;
            UInt16 readLength = 9;

            iResult = (byte)Device_Read(G2MemBank.EPC, filterOffset, iFilterDataLength, pFilterData,
                G2MemBank.EPC, readOffset, readLength, ref pReadData, Antenna);
            //LogService.Instance.Info("过滤偏移：[" + filterOffset + "]，过滤长度：[" + iFilterDataLength + "]，过滤数据：[" + StringChange.bytesToHexStr(pFilterData, pFilterData.Length) + "],读取偏移：["+ readOffset + "],读取长度：["+ readLength + "]");
            if (iResult > 0)
            {
                //LogService.Instance.Info("函数调用:Device_GetOneIdentifyData成功，返回标签数据为：" + Encoding.ASCII.GetString(pReadData, 0, pReadData.Length) + "原始数据为：" + StringChange.bytesToHexStr(pReadData, pReadData.Length));
                return iResult;
            }
            else
            {
                //LogService.Instance.Info("函数调用:Device_GetOneIdentifyData读取失败，进入失败重读");
                iResult = (byte)Device_Read(G2MemBank.EPC, filterOffset, iFilterDataLength, pFilterData,
                 G2MemBank.EPC, readOffset, readLength, ref pReadData, Antenna, ReadCounts);
            }
            return iResult;

        }
        public UInt16 Device_Write(G2MemBank filterMembank, UInt16 filterWordPtr, UInt16 filterWordCnt, Byte[] filterData,
  G2MemBank Membank, UInt16 WordPtr, UInt16 WordCnt, Byte[] pWriteData, byte Antenna)
        {
            mut.WaitOne();
            byte iResult = 0;
            byte[] pReadData = null;
            UInt16 iReadLen = 0;
            try
            {
                LogService.Instance.Info("函数调用:Device_Write，写入内容：" + StringChange.bytesToHexStr(pWriteData, WordCnt));
                m_GlobalSem.WaitOne(-1, false);
                Fuchs_Write(filterMembank, filterWordPtr, filterWordCnt, filterData, Membank, WordPtr, WordCnt, pWriteData, Antenna);
                m_GlobalSem.Release();
                for (int i = 0; i < 3; i++)
                {
                    LogService.Instance.Debug("Device_Write 写入的长度: " + WordCnt);
                    iReadLen = Device_Read(filterMembank, filterWordPtr, filterWordCnt, filterData, Membank, WordPtr, WordCnt, ref pReadData, Antenna);
                    LogService.Instance.Debug("Device_Read 读取的长度: " + iReadLen);
                    if (iReadLen == WordCnt)
                    {
                        if (StringChange.CompareBytes(pReadData, pWriteData, WordCnt))    //写入的跟读出的一样
                        {
                            return 1;
                        }
                        else    //写入的跟读出的不一样
                        {
                            iResult = 2;
                        }
                    }
                    else
                    {
                        iResult = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("Device_Write异常：" + ex.Message);
                mut.ReleaseMutex();
                return 0;
            }
            mut.ReleaseMutex();
            return iResult;
        }

        private UInt16 Fuchs_Write(G2MemBank filterMembank, ushort filterWordPtr, ushort filterWordCnt, byte[] filterData, G2MemBank Membank, ushort WordPtr, ushort WordCnt, byte[] pWriteData, byte Antenna)
        {
            byte[] u16byte = new byte[2];
            byte iResult = 0;
            int iSendDataLen;
            try
            {
                MessagePack pMessagePack = new MessagePack();
                //00 14 0D E4 00 00 30 00 51 37 31 31 35 30 30 30 31 00 00 00 1号超高频读头写入报文示例
                if (Antenna > 4)    //超高频读头
                {
                    iSendDataLen = 20;  //发送指令帧长度
                    pMessagePack.m_pData = new byte[iSendDataLen];
                    Array.Clear(pMessagePack.m_pData, 0, iSendDataLen);//清空为0
                    pMessagePack.m_pData[0] = 0X00;    //
                    pMessagePack.m_pData[1] = 0X14;    //
                    pMessagePack.m_pData[2] = 0X0D;    //
                    if (Antenna == 5)
                    {
                        pMessagePack.m_pData[3] = 0XE2;    //1号超高频读头
                    }
                    else if (Antenna == 6)
                    {
                        pMessagePack.m_pData[3] = 0XE4;    //2号超高频读头
                    }
                    else if (Antenna == 7)
                    {
                        pMessagePack.m_pData[3] = 0XE6;    //3号超高频读头
                    }
                    else if (Antenna == 8)
                    {
                        pMessagePack.m_pData[3] = 0XE6;    //4号超高频读头
                    }
                    pMessagePack.m_pData[4] = 0X00;      //
                    pMessagePack.m_pData[5] = 0X00;      //
                    pMessagePack.m_pData[6] = 0X30;      //
                    pMessagePack.m_pData[7] = 0X00;      //
                    if (WordCnt > 0)
                    {
                        Array.Copy(pWriteData, 0, pMessagePack.m_pData, 8, WordCnt); //写入数据
                    }
                    pMessagePack.m_pData[17] = 0X00;
                    pMessagePack.m_pData[18] = 0X00;
                    pMessagePack.m_pData[19] = 0X00;
                }
                else if (Antenna < 5)    //高频读头
                {
                    //00 12 40 32 00 00 31 32 33 34 35 36 37 38 39 00 00 00
                    iSendDataLen = 6 + WordCnt;  //高频写标签指令帧长度
                    pMessagePack.m_pData = new byte[iSendDataLen];
                    Array.Clear(pMessagePack.m_pData, 0, iSendDataLen);//清空为0
                    pMessagePack.m_pData[0] = 0X00;    //
                    pMessagePack.m_pData[1] = (byte)(WordCnt + 6);    //
                    pMessagePack.m_pData[2] = 0X40;    //
                    pMessagePack.m_pData[3] = (byte)(0X30 + (Antenna * 2));
                    pMessagePack.m_pData[4] = 0X00;      //
                    pMessagePack.m_pData[5] = 0X00;      //

                    if (WordCnt > 0)
                    {
                        Array.Copy(pWriteData, 0, pMessagePack.m_pData, 6, WordCnt); //写入数据
                    }
                    //pMessagePack.m_pData[15] = 0X00;
                    //pMessagePack.m_pData[16] = 0X00;
                    //pMessagePack.m_pData[17] = 0X00;

                    //Array.Reverse(pMessagePack.m_pData, 6, 4);
                    //Array.Reverse(pMessagePack.m_pData, 10, 4);
                    //Array.Reverse(pMessagePack.m_pData, 14, 4);
                }
                //m_WriteSem.Release(1);
                m_WriteSem.WaitOne(1, false);
                if (m_ICommunicateService.SendMessage(pMessagePack))   //发送报文成功
                {
                    if (m_WriteSem.WaitOne(2000, false))   //等待结果,并取结果返回。
                    {
                        if (m_bWriteSuccedTag == true) //有数据，正常
                        {
                            iResult = 1;
                        }
                        else
                        {
                            iResult = 0;
                        }
                    }
                    else   //超时
                    {
                        iResult = 0;
                    }
                }
                else
                {
                    LogService.Instance.Info("发送写入命令失败");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("Fuchs_Write异常：" + ex.Message);
                return 0;
            }
            return iResult;
        }
        public bool Device_SetRf(int iDbi, byte Antenna, WriteOrRead RorW) //设置CT读头模式高频or超高频
        {
            bool bResult = false;
            try
            {
                MessagePack pMessagePack = new MessagePack();
                pMessagePack.m_pData = new byte[6];
                Array.Clear(pMessagePack.m_pData, 0, 6);//清空为0
                if (Antenna < 5)
                {
                    //设置高频CT 00 06 04 02 32 30
                    pMessagePack.m_pData[0] = 0X00;
                    pMessagePack.m_pData[1] = 0X06;
                    pMessagePack.m_pData[2] = 0X04;      //设置CT
                    //高频天线号 1，2，3，4
                    pMessagePack.m_pData[3] = (byte)(Antenna * 2);
                    pMessagePack.m_pData[4] = 0x32;
                    pMessagePack.m_pData[5] = 0x30;
                }
                else if (Antenna > 4)   // 约定5,6,7,8天线号为超高频读头
                {
                    //设置超高频读头CT 00 06 04 04 38 30
                    pMessagePack.m_pData[0] = 0X00;
                    pMessagePack.m_pData[1] = 0X06;
                    pMessagePack.m_pData[2] = 0X04;      //设置CT
                    if (Antenna == 5)
                    {
                        pMessagePack.m_pData[3] = 0X02;
                    }
                    else if (Antenna == 6)
                    {
                        pMessagePack.m_pData[3] = 0X04;
                    }
                    else if (Antenna == 7)
                    {
                        pMessagePack.m_pData[3] = 0X06;
                    }
                    else if (Antenna == 8)
                    {
                        pMessagePack.m_pData[3] = 0X08;
                    }
                    pMessagePack.m_pData[4] = 0x38;
                    pMessagePack.m_pData[5] = 0x30;
                }
                m_SetDbmSem.WaitOne(1, false);
                if (m_ICommunicateService.SendMessage(pMessagePack))   //发送报文成功
                {
                    if (m_SetDbmSem.WaitOne(1000, false))   //等待结果,并取结果返回。
                    {
                        LogService.Instance.Info("传感器设置CT成功！");
                        bResult = true;
                    }
                    else   //超时
                    {
                        bResult = false;
                        LogService.Instance.Info("传感器设置CT失败！");
                    }
                }
                else
                {
                    LogService.Instance.Info("传感器设置CT超时！");
                    bResult = false;
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("传感器设置CT异常：" + ex.Message);
                bResult = false;
            }
            return bResult;
        }


        #region 修改按时间段盘点需求

        public bool Device_StopIdentify(byte Antenna)   //停止指令
        {
            bool bResult = false;
            try
            {
                MessagePack pMessagePack = new MessagePack();
                if (Antenna < 5)    //高频读头发送停止连续盘点指令
                {
                    pMessagePack.m_pData = new byte[6];
                    Array.Clear(pMessagePack.m_pData, 0, 6);//清空为0
                    pMessagePack.m_pData[0] = 0X00;
                    pMessagePack.m_pData[1] = 0X06;
                    pMessagePack.m_pData[2] = 0X02;      //读Data区
                                                         //天线号1，2，3，4
                    pMessagePack.m_pData[3] = (byte)(0X30 + (Antenna * 2));
                    pMessagePack.m_pData[4] = 0x00;
                    pMessagePack.m_pData[5] = 0x00;
                }
                else if (Antenna > 4)   //超高频读头发送停止连续盘点指令
                {
                    pMessagePack.m_pData = new byte[4];
                    Array.Clear(pMessagePack.m_pData, 0, 4);//清空为0
                    pMessagePack.m_pData[0] = 0X00;
                    pMessagePack.m_pData[1] = 0X04;
                    pMessagePack.m_pData[2] = 0X02;
                    if (Antenna == 5)
                    {
                        pMessagePack.m_pData[3] = 0X02;
                        AntList[Antenna - 1].UHFAntenna = true;
                    }
                    else if (Antenna == 6)
                    {
                        pMessagePack.m_pData[3] = 0X04;
                        AntList[Antenna - 1].UHFAntenna = true;
                    }
                    else if (Antenna == 7)
                    {
                        pMessagePack.m_pData[3] = 0X06;
                        AntList[Antenna - 1].UHFAntenna = true;
                    }
                    else if (Antenna == 8)
                    {
                        pMessagePack.m_pData[3] = 0X08;
                        AntList[Antenna - 1].UHFAntenna = true;
                    }
                }
                //m_StopSem.WaitOne(1, false);
                //AntList[Antenna - 1].m_StopResult.WaitOne(1, false);
                if (m_ICommunicateService.SendMessage(pMessagePack))   //发送报文成功
                {

                    if (AntList[Antenna - 1].m_StopResult.WaitOne(5000, false))   //等待结果,并取结果返回。
                    {
                        LogService.Instance.Info("第[" + Antenna + "]路传感器，发送停止连续识别命令成功！");
                        bResult = true;
                    }
                    else   //超时
                    {
                        LogService.Instance.Info("第[" + Antenna + "]路传感器，发送停止连续识别命令超时！");
                        bResult = false;
                    }
                }
                else
                {
                    LogService.Instance.Info("第[" + Antenna + "]路传感器，发送停止连续识别命令失败！");
                    bResult = false;
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("第[" + Antenna + "]路传感器，发送停止连续识别命令异常：" + ex.Message);
                bResult = false;
            }
            //finally
            //{
            //    m_GlobalSem.Release();
            //}

            return bResult;
        }

        private void WaitTimePanDianData(byte Antenna, int timeout, bool atuoRead)    //MES主动盘点等待数据返回函数
        {
            LogService.Instance.Info("第[" + Antenna + "]路传感器，测试1");
            AntList[Antenna - 1].m_WaitResult.WaitOne(1, false);
            LogService.Instance.Info("第[" + Antenna + "]路传感器，测试2");
            if (AntList[Antenna - 1].m_WaitResult.WaitOne(timeout, false))
            {
                LogService.Instance.Debug("收到数据，当前第" + Antenna + "号传感器类型readType = " + AntList[Antenna - 1].readType);
                if (atuoRead)
                {
                    LogService.Instance.Info("第[" + Antenna + "]路传感器，自动读释放信号量");
                }
                else
                {
                    LogService.Instance.Info("第[" + Antenna + "]路传感器，MES读释放信号量");
                }
                AntList[Antenna - 1].readType = 0;
                LogService.Instance.Debug("收到数据，重新赋值后第" + Antenna + "号传感器类型readType = " + AntList[Antenna - 1].readType);
                AntList[Antenna - 1].m_Waiting.Release();
            }
            else
            {
                LogService.Instance.Debug("未收到数据，当前第" + Antenna + "号传感器类型readType = " + AntList[Antenna - 1].readType);
                if (atuoRead)
                {
                    LogService.Instance.Info("第[" + Antenna + "]路传感器，自动读未释放信号量");
                    if (RecvIdentifyDataEvent != null)
                    {
                        RecvIdentifyDataEvent(0, null, Antenna, m_iDeviceId, m_strIp);
                    }                 
                }
                else
                {
                    LogService.Instance.Info("第[" + Antenna + "]路传感器，MES读未释放信号量");
                    if (RecvIdentifyData_ToMES_Event != null)
                    {
                        RecvIdentifyData_ToMES_Event(0, null, Antenna, m_iDeviceId, m_strIp);
                    }
                }
                AntList[Antenna - 1].readType = 0;
                LogService.Instance.Debug("未收到数据，重新赋值后第" + Antenna + "号传感器类型readType = " + AntList[Antenna - 1].readType);
                AntList[Antenna - 1].m_Waiting.Release();
                Device_StopIdentify(Antenna);
            }

        }
        public bool Device_BeginIdentify(byte Antenna, int timeout, bool AutoRead)
        {
            #region 等第一次读取信号释放，再进行下一次
            //if (AntList[Antenna - 1].readType > 0)
            //{
            //    if (AntList[Antenna - 1].IsReading)//上次触发未返回
            //    {
            //        AntList[Antenna - 1].m_Waiting.WaitOne(timeout, false);
            //        LogService.Instance.Debug("-------------------上次读取未释放信号量");
            //        //已经有读取的信号了等待信号量释放,且不再进行盘点
            //        return false;
            //    }             
            //}
            //else
            //{
            //    if (AutoRead)
            //    {
            //        AntList[Antenna - 1].readType = 1;//自动读取
            //    }
            //    else
            //    {
            //        AntList[Antenna - 1].readType = 2;//主动读取
            //    }
            //    AntList[Antenna - 1].IsReading = true;
            //}
            #endregion
            LogService.Instance.Debug("开始连续识别，第" + Antenna + "号传感器类型readType = " + AntList[Antenna - 1].readType);
            #region 接收信号排队进行读取
            if (AntList[Antenna - 1].readType > 0)
            {
                AntList[Antenna - 1].m_Waiting.WaitOne(1, false);
                //已经有读取的信号了等待信号量释放
                if (AntList[Antenna - 1].m_Waiting.WaitOne(timeout, false))
                {
                    return false;
                    //LogService.Instance.Debug("上次读取已返回数据，再次进行读取后第" + Antenna + "号传感器类型readType = " + AntList[Antenna - 1].readType);
                    //AntList[Antenna - 1].readType = AutoRead ? 1 : 2;
                    //LogService.Instance.Debug("上次读取已返回数据，重新赋值后第" + Antenna + "号传感器类型readType = " + AntList[Antenna - 1].readType);
                }
                else
                {
                    LogService.Instance.Debug("上次读取未返回数据，再次进行读取后第" + Antenna + "号传感器类型readType = " + AntList[Antenna - 1].readType);
                    //上一次执行没有返回
                    AntList[Antenna - 1].readType = AutoRead ? 1 : 2;
                    LogService.Instance.Debug("上次读取未返回数据，重新赋值后第" + Antenna + "号传感器类型readType = " + AntList[Antenna - 1].readType);
                }
            }
            else
            {

                AntList[Antenna - 1].readType = AutoRead ? 1 : 2;
                LogService.Instance.Debug("赋值后第" + Antenna + "号传感器类型readType = " + AntList[Antenna - 1].readType);
            }
            #endregion 
            byte[] u16byte = new byte[2];
            bool bResult = false;
            try
            {
                MessagePack pMessagePack = new MessagePack();
                if (Antenna < 5)
                {
                    pMessagePack.m_pData = new byte[6];
                    Array.Clear(pMessagePack.m_pData, 0, 6);//清空为0
                    pMessagePack.m_pData[0] = 0X00;
                    pMessagePack.m_pData[1] = 0X06;
                    pMessagePack.m_pData[2] = 0X19;      //读Data区
                    //天线号 1，2，3，4
                    pMessagePack.m_pData[3] = (byte)(0X30 + (Antenna * 2));

                    pMessagePack.m_pData[4] = 0x00;
                    pMessagePack.m_pData[5] = 0x00;
                    IsUHFAnt = false;
                }
                else if (Antenna > 4)   // 约定5,6,7,8天线号为超高频读头
                {
                    pMessagePack.m_pData = new byte[4];
                    Array.Clear(pMessagePack.m_pData, 0, 4);//清空为0
                    pMessagePack.m_pData[0] = 0X00;
                    pMessagePack.m_pData[1] = 0X04;
                    pMessagePack.m_pData[2] = 0X71;
                    if (Antenna == 5)
                    {
                        pMessagePack.m_pData[3] = 0X02;
                    }
                    else if (Antenna == 6)
                    {
                        pMessagePack.m_pData[3] = 0X04;
                    }
                    else if (Antenna == 7)
                    {
                        pMessagePack.m_pData[3] = 0X06;
                    }
                    else if (Antenna == 8)
                    {
                        pMessagePack.m_pData[3] = 0X08;
                    }
                    IsUHFAnt = true;
                }
                s_UHFBeginEvent.WaitOne(1,false);
                if (m_ICommunicateService.SendMessage(pMessagePack))   //发送报文成功
                {
                    //启动等待数据接受线程  
                    Thread m_bgwWaitingForData = new Thread(() => WaitTimePanDianData(Antenna, timeout, AutoRead));
                    m_bgwWaitingForData.IsBackground = true; 
                    m_bgwWaitingForData.Start();
                    if (IsUHFAnt)//超高频读头发送连续识别
                    {
                        if (s_UHFBeginEvent.WaitOne(2000, false))   //等待结果,并取结果返回。
                        {
                            LogService.Instance.Info("第[" + Antenna + "]路超高频传感器，发送连续识别命令成功！");
                            bResult = true;
                        }
                        else   //超时
                        {
                            bResult = false;
                            LogService.Instance.Info("第[" + Antenna + "]路超高频传感器，发送连续识别命令超时！");
                        }
                    }
                    else
                    {
                        if (s_BeginEvent.WaitOne(2000, false))   //等待结果,并取结果返回。
                        {
                            LogService.Instance.Info("第[" + Antenna + "]路高频传感器，发送连续识别命令成功！");
                            bResult = true;
                        }
                        else   //超时
                        {
                            bResult = false;
                            LogService.Instance.Info("第[" + Antenna + "]路高频传感器，发送连续识别命令超时！");
                        }
                    }
                }
                else
                {
                    LogService.Instance.Info("第[" + Antenna + "]路传感器，发送开始连续识别命令失败！");
                    bResult = false;
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("第[" + Antenna + "]路传感器，发送开始连续识别命令异常：" + ex.Message);
                bResult = false;
            }
            //finally
            //{
            //    m_GlobalSem.Release();
            //}
            return bResult;
        }
        #endregion
        #region 未实现的函数

        public string Device_GetOneIdentifyData(Byte Antenna, UInt16 Timedout)
        {
            string strResult = "";
            int iSendDataLen = 0; 
            try
            {
                iSendDataLen = 11;
                MessagePack pMessagePack = new MessagePack();
                pMessagePack.m_pData = new byte[iSendDataLen];
                Array.Clear(pMessagePack.m_pData, 0, iSendDataLen);//清空为0
                pMessagePack.m_pData[0] = 0x00;
                pMessagePack.m_pData[1] = 0x0B;
                pMessagePack.m_pData[2] = 0XBF;
                pMessagePack.m_pData[3] = (byte)(Antenna * 2);
                pMessagePack.m_pData[4] = 0x00;
                pMessagePack.m_pData[5] = 0x55;
                pMessagePack.m_pData[6] = 0x51;
                pMessagePack.m_pData[7] = 0x56;
                pMessagePack.m_pData[8] = 0x00;
                pMessagePack.m_pData[9] = 0x01;
                pMessagePack.m_pData[10] = 0x53;
                m_SetSignelModelSem.WaitOne(1, false);
                if (m_ICommunicateService != null)
                {
                    if (m_ICommunicateService.SendMessage(pMessagePack))   //发送报文成功
                    {
                        if (m_SetSignelModelSem.WaitOne(2000, false))   //等待结果,并取结果返回。
                        {
                            //LogService.Instance.Info("单标签模式设置成功。");
                            strResult = "成功";        //通讯连接和读写器都正常
                        }
                        else                    //超时
                        {
                            //LogService.Instance.Info("发送心跳报文超时。");
                            strResult = "超时";       //通讯连接器正常，读写器故障
                        };
                    }
                    else
                    {
                        //通讯连接器失败或网络故障
                        //LogService.Instance.Info("发送心跳报文失败，通讯故障。");
                        strResult = "失败";
                    }
                }
                else
                {
                    return strResult;
                }
            }
            catch (Exception ex)
            {
                LogService.Instance.Error("Device_GetOneIdentifyData：" + ex.Message);
                strResult = "异常";
            }
            return strResult;
        }
        public string Device_GetOneIdentifyData_Finish(byte Antenna, ushort Timedout)
        {
            mut.WaitOne();

            return "";
        }
        public Byte Device_GetOneIdentifyData_Finish(ref byte[] pReadData, byte Antenna, ushort Timedout)
        {
            mut.WaitOne();
            byte iResult = 0;

            return iResult;
        }
        public ushort Device_GetReportData(ref byte[] pReadData, Byte Antenna, UInt32 Timedout)
        {
            mut.WaitOne();
            byte[] pTemp = null;
            byte iReadLen = 0;
            if ((iReadLen = Device_GetOneIdentifyData(ref pTemp, Antenna, (UInt16)Timedout, 5)) > 0)
            {
                LogService.Instance.Info("Device_GetReportData获取自报数据" + "数据长度" + iReadLen);
                pReadData = new byte[iReadLen + 1];
                pReadData[0] = iReadLen;
                Array.Copy(pTemp, 0, pReadData, 1, iReadLen);
                mut.ReleaseMutex();
                return (ushort)(iReadLen + 1);
            }
            else
            {
                mut.ReleaseMutex();
                return 0;
            }
        }
        public ushort Device_GetIdentifyData(ref byte[] pReadData, byte Antenna)
        {
            ushort iResult = 0;
            try
            {
                LogService.Instance.Info("函数调用:Device_GetIdentifyData");
                lock (m_IdentifyData)
                {
                    if ((m_IdentifyDataLen > 0 && m_IdentifyData[m_IdentifyDataLen - 1] == (Antenna + 1)) || Antenna == 255)
                    {
                        iResult = (UInt16)(m_IdentifyDataLen - 1);
                        pReadData = new byte[m_IdentifyDataLen - 1];
                        pReadData[0] = (byte)(m_IdentifyDataLen - 3);
                        pReadData[1] = (byte)Antenna;
                        Array.Copy(m_IdentifyData, 0, pReadData, 2, m_IdentifyDataLen - 3);
                        m_IdentifyDataLen = 0;
                        LogService.Instance.Info("Device_GetIdentifyData:" + StringChange.bytesToHexStr(pReadData, pReadData.Length));
                        return iResult;
                    }
                    else
                    {
                        return 0;
                    }
                }

            }
            catch (Exception ex)
            {
                LogService.Instance.Error("获得识别期间数据异常：" + ex.Message);
                return 0;
            }
        }

        #endregion
    }

}
