RFIDManager.cs 10.9 KB
using Asa.RFID;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace OnlineStore.DeviceLibrary
{
    public  class RFIDManager
    {
        public static Dictionary<string, Reader> RFReaderMap = new Dictionary<string, Reader>();

        private static List<string> RfIPList = new List<string>();
        private static System.Timers.Timer conTimer = null;

        public  static void ConnectRFIOList(List<string> rfioNameList)
        {
            try { 
            if (conTimer == null)
            {
                conTimer = new System.Timers.Timer();
                conTimer.AutoReset = true;
                conTimer.Interval = 60000;
                conTimer.Elapsed += ConTimer_Elapsed;
            }
            conTimer.Enabled = false;
            RfIPList = new List<string>(rfioNameList);
            foreach (string ip in rfioNameList)
            {
                ConnectionIP(ip);
            }
            if (RfIPList.Count > 0)
            {
                conTimer.Start();
            }
            }catch(Exception ex)
            {
                LogUtil.error("ConnectRFIOList出错:" + ex.ToString());
            }
        }
        private static int DefaultTrayNum = ConfigAppSettings.GetIntValue(Setting_Init.DefaultTrayNum);
        /// <summary>
        /// 获取托盘编码
        /// </summary> 
        public static int GetTrayNum(int subType, bool isClear = false)
        {
            if (DefaultTrayNum > 0)
            {
                return DefaultTrayNum;
            }
            //  return 9;
            if (subType.Equals(104))
            {
                return LineManager.Line.Sw23TrayNum;
            }
            else if (subType.Equals(101))
            {
                return LineManager.Line.Sw41TrayNum;
            }

            string ip = GetRFIP(subType);
            //获取盘号
            RFIDData data = ReadRFID(ip, isClear);
            if (data != null)
            {
                if (data.RFType.Equals((byte)'E'))
                {
                    return data.Num;
                }
                else if (data.RFType > 0)
                {
                    LogUtil.error("RFID [ " + ip + " ] 读到数据 " + data.ToStr() + " 返回盘号  0");
                }
                else
                {
                    LogUtil.debug("RFID [ " + ip + " ] 读到数据 " + data.ToStr() + " 返回盘号  0");
                }
                return 0;
            }

            return 0;
        }
        public static RFIDData GetShelfData(int subType)
        {
            string ip = GetRFIP(subType, 1);
            return ReadRFID(ip);
        }


        public static RFIDData ReadRFID(string ip, bool isClear = false)
        {
            try
            {
                if (String.IsNullOrEmpty(ip).Equals(false) && LineManager.Line.rfidList.Contains(ip))
                {
                    RFIDData data = new RFIDData(RfidReader.Read(ip));
                    if (isClear)
                    {
                        RfidReader.Clear(ip);
                    }
                    return data;
                }
            }
            catch (Exception ex)
            {
                //LogUtil.error("ReadRFID["+ip+"]出错:" + ex.ToString());
            }
            return new RFIDData(-1, -1);
        }

        public static string GetRFIP(int subType, int rtType = 0)
        {
            string ip = "";
            string rtName = DeviceConfig.RFIP_Str + "_" + subType.ToString().PadLeft(3, '0');
            if (rtType > 0)
            {
                rtName += "-" + rtType.ToString();
            }
            if (DeviceConfig.ProRFIpMap.ContainsKey(rtName))
            {
                ip = DeviceConfig.ProRFIpMap[rtName];
            }
            return ip;
        }


        private static bool isProcess = false;
        private static DateTime lastTime = DateTime.Now;

        public static bool IsConnect(string ip)
        {
            if (RFReaderMap.ContainsKey(ip))
            {
                return true;
            }
            return false;
        }

        private static void ConTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            TimeSpan span = DateTime.Now - lastTime;
            if (span.TotalMinutes < RfIPList.Count && isProcess)
            {
                return;
            }
            isProcess = true;
            lastTime = DateTime.Now;
            try
            {
                List<string> list = new List<string>(RfIPList);
                if (list.Count > 0)
                {
                    LogUtil.info("开始重连RFIP模块 ------------");
                    foreach (string ip in list)
                    {
                        ConnectionIP(ip);
                    }
                    LogUtil.info("结束重连RFIP模块 ------------");
                }
                GC.Collect();
            }
            catch (Exception ex)
            {
                LogUtil.error("RFIP ConTimer_Elapsed 出错: " + ex.ToString());
            }
            isProcess = false;
        }

        public static bool ConnectionIP(string rfid)
        {
            Reader rfidReader = null;
            CloseRFID(rfid);
            string logName = "RFIP模块[" + rfid + "] ";
            try
            {
                LogUtil.debug("开始连接" + logName + ",尝试重连3次");

                rfidReader = new Reader();
                bool result = rfidReader.Connect(rfid,true);
                if (result)
                {
                    //rfidReader.AutoScan(true);
                    LogUtil.info("连接 " + logName + "成功");
                    RFReaderMap.Add(rfid, rfidReader);
                    if (RfIPList.Contains(rfid))
                    {
                        RfIPList.Remove(rfid);
                    }
                    return true;

                }
                else
                {
                    LogUtil.error("连接 " + logName + "失败" + "");
                }
                Thread.Sleep(5); 
            }
            catch (Exception error)
            {
                LogUtil.error("连接RFIP模块 " + logName + " 出错:" + error.ToString());
            }
            return false;
        }

        public static void CloseRFID(string rfid)
        {
            try
            {
                if (RFReaderMap.ContainsKey(rfid))
                {
                    Reader rfidReader = RFReaderMap[rfid];
                    if (null != rfidReader)
                    {
                        rfidReader.Close();
                        rfidReader = null;
                    }
                    RFReaderMap.Remove(rfid);
                }
            }catch(Exception exx)
            {
                LogUtil.error("关闭rfid【"+rfid+"】出错:" + rfid);
            }
        }

        public  static void CloseAllConnection()
        {
            foreach (Reader reader in RFReaderMap.Values)
            {
                reader.Close();
            }
        }
      
        public static RFIDData ReadData(string IP)
        { 
            byte[] reviceData = ReadData(IP, 3);
            if (reviceData != null)
            {
                return new RFIDData(reviceData);
            }
            return null;
        }
     
        private static bool FindRFID(string IP)
        {
            try
            {
                Reader rfReader = getRfReader(IP);
                if (rfReader != null)
                {
                    return rfReader.FindRFID();
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("RFIP FindRFID [" + IP + "] 出错 :" + ex.ToString());
            }
            return false;
        }
        private static byte[] ReadData(string IP, int reReadCount = 1,int startIndex=0,int readLength=4)
        {
            try
            {
                Reader rfReader = getRfReader(IP);
                if (rfReader == null)
                {
                    return null;
                }
                for (int i = 1; i <= reReadCount; i++)
                {
                    byte[] reviceData = rfReader.Read(startIndex, readLength);
                    if (reviceData != null)
                    {
                        return reviceData;
                    }
                    LogUtil.error("RFIP ReadData [" + IP + "] 第" + i + "次失败 ");
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("RFIP ReadData [" + IP + "] 出错 :" + ex.ToString());
            }
            return null;
        }
        private static bool WriteData(string IP, byte[] data, int reWriteCount = 1)
        {
            try
            {
                Reader rfReader = getRfReader(IP);
                if (rfReader == null)
                {
                    return false;
                }
                for (int i = 1; i <= reWriteCount; i++)
                {
                    bool result = rfReader.Write(data);
                    if (result)
                    {
                        return result;
                    }
                    LogUtil.error("RFIP WriteData [" + IP + "] 第" + i + "次失败:");
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("RFIP WriteData [" + IP + "]   出错 :" + ex.ToString());
            }
            return false;
        }
        private static Reader getRfReader(string IP)
        {
            Reader rfReader = null;
            if (RFReaderMap.ContainsKey(IP))
            {
                rfReader = RFReaderMap[IP];
            }
            else
            {
                LogUtil.error("getRfReader 没有连接RFIP模块:" + IP);
            }
            return rfReader;
        }
    }
    public class RFIDData
    {
        /// <summary>
        /// RFID类型,区分是料架还是托盘,托盘E=69,A=65
        /// </summary>
        public int RFType = 0;
        /// <summary>
        /// 托盘编号,从1-32
        /// </summary>
        public int Num = 0;

        public RFIDData(int num, int t)
        {
            this.RFType = t;
            this.Num = num;
        }

        public RFIDData(byte[] data)
        {
            try
            {
                if (data != null && data.Length > 2)
                {
                    RFType = data[1];
                    Num = Convert.ToInt32(data[2]);
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("RFIP 数据【" + data + "】 获取编码失败");
            }
        }
        public byte[] ToData()
        {
            return new byte[] { (byte)RFType, (byte)Num };
        }
        public string ToStr()
        {
            return "  [" + RFType + "],[" + Num + "] ";
        }


    }
}