Common.cs 6.5 KB

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Asa.RFID
{
    internal class HFReaderInfo
    {
        internal string IP;
        internal string Mac;
        internal int Port;
        internal int Func;
        internal byte[] Buffer;
        internal byte[] ID;
        internal byte ComAddr;

        public HFReaderInfo()
        {
            Func = 0;
            Buffer = new byte[28 * 4];
            ID = new byte[8];
        }

        public HFReaderInfo(string ip) : this()
        {
            IP = ip;
            string[] aa = ip.Split('.');
            ComAddr = Convert.ToByte(aa[3]);
            Port = 6000 + Convert.ToInt32(aa[3]);
        }
    }

    /// <summary>
    /// IP地址操作
    /// </summary>
    public static class IP
    {
        private static List<HFReaderInfo> info = new List<HFReaderInfo>();
        private static UdpClient udp;

        private const int PORT = 51060;

        /// <summary>
        /// 查找IP地址
        /// </summary>
        /// <param name="localIP"></param>
        /// <returns></returns>
        public static string[] Find(string localIP)
        {
            info.Clear();
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 65535);
            byte[] arr = Encoding.ASCII.GetBytes("X");
            IPEndPoint local = new IPEndPoint(IPAddress.Parse(localIP), PORT);
            udp = new UdpClient(local);
            udp.Send(arr, arr.Length, ep);
            System.Threading.Thread.Sleep(50);

            int count = 0;
            int time = 0;
            System.Threading.Thread tTemp = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ReceiveIP));
            tTemp.Start(ep);
            while (true)
            {
                if (info.Count == count)
                    time += 50;
                else
                {
                    time = 0;
                    count = info.Count;
                }
                if (time >= 800)
                {
                    tTemp.Abort();
                    tTemp = null;
                    break;
                }
                System.Threading.Thread.Sleep(50);
            }

            udp.Close();
            string[] ip = new string[info.Count];
            for (int i = 0; i < ip.Length; i++)
                ip[i] = info[i].IP;
            return ip;

        }

        /// <summary>
        /// 修改IP地址,需要先查找IP
        /// </summary>
        /// <param name="localIP">本地IP</param>
        /// <param name="beforeIP">修改前的IP</param>
        /// <param name="afterIP">修改后的IP</param>
        /// <returns></returns>
        public static bool Modify(string localIP, string beforeIP, string afterIP)
        {
            int idx = info.FindIndex(s => s.IP == beforeIP);
            if (idx == -1) return false;
            IPEndPoint local = new IPEndPoint(IPAddress.Parse(localIP), PORT);
            UdpClient udp = new UdpClient(local);
            string[] ss = afterIP.Split('.');
            string port = "6" + ss[3];

            try
            {
                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(info[idx].IP), 65535);
                byte[] buff;

                buff = Encoding.ASCII.GetBytes("W" + info[idx].Mac);
                udp.Send(buff, buff.Length, ep);
                System.Threading.Thread.Sleep(100);

                buff = Encoding.ASCII.GetBytes("L");
                udp.Send(buff, buff.Length, ep);
                System.Threading.Thread.Sleep(50);

                buff = Encoding.ASCII.GetBytes("SPN" + port + "|33");
                udp.Send(buff, buff.Length, ep);
                System.Threading.Thread.Sleep(50);

                buff = Encoding.ASCII.GetBytes("SIP" + afterIP + "|34");
                udp.Send(buff, buff.Length, ep);
                System.Threading.Thread.Sleep(100);

                buff = Encoding.ASCII.GetBytes("E|35");
                udp.Send(buff, buff.Length, ep);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                udp.Close();
            }
        }

        /// <summary>
        /// 获取本地IPv4地址
        /// </summary>
        /// <returns></returns>
        public static string[] GetLocal()
        {
            List<string> str = new List<string>();
            IPAddress[] add = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            foreach (IPAddress ip in add)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                    str.Add(ip.ToString());
            }
            return str.ToArray();
        }




        private static void ReceiveIP(object obj)
        {
            IPEndPoint ep = (IPEndPoint)obj;

            while (true)
            {
                byte[] buff = udp.Receive(ref ep);
                HFReaderInfo ri = new HFReaderInfo { IP = ep.Address.ToString() };
                if (buff == null || buff.Length < 20 || buff[0] != 0x41)
                    continue;
                bool cut = true;
                for (int i = 0; i < buff.Length; i++)
                {
                    if (buff[i] == 0x2F)
                    {
                        if (cut)
                        {
                            ri.Mac = Encoding.ASCII.GetString(buff, 1, i - 1);
                            cut = false;
                        }
                        else
                        {
                            //info.Port = Convert.ToInt32(Encoding.ASCII.GetString(buff, start, i - start));
                            break;
                        }
                    }
                }
                info.Add(ri);
                System.Threading.Thread.Sleep(5);
            }
        }


    }

    public enum Error
    {
        OK = 0,
        LengthError = 1,
        OperationNotSupport = 2,
        RfClosed = 5,
        EEPROM = 6,
        MultipleError = 7,
        TimeOut = 10,
        MoreUID = 11,
        ISOError = 12,
        NoElectronicTag = 14,
        OperationError = 15,
        BlockError = 16,
        BlockLockedAndCntLock = 17,
        BlockLockedAndCntWrite = 18,
        BlockCntOperate = 19,
        BlockCntLock = 20,
        CommunicationError = 48,
        RetCRCError = 49,
        DataLengthError = 50,
        CommunicationBusy = 51,
        ExecuteCmdBusy = 52,
        ComPortOpened = 53,
        ComPortClose = 54,
        InvalidHandle = 55,
        InvalidPort = 56
    }
}