public bool Open(uint port)
        {
            bool res = ComPort.OpenComPort(port, _Baudrate);

            if (res)
            {
                this.port = (int)port;
                return(true);
            }
            else
            {
                this.port = -1;
                return(false);
            }
        }
 public byte[] Recive(uint size, uint timeout)
 {
     if (port >= 0)
     {
         byte[] res = new byte[size];
         int    n   = ComPort.Recive((uint)port, res, (uint)res.Length, timeout);
         // if (n > 0)
         //     System.Diagnostics.Trace.WriteLine("Serial GetData : " + Program.bin_to_asc(res, n));
         if (n == size)
         {
             return(res);
         }
         else if (n > 0)
         {
             byte[] ss = new byte[n];
             for (int i = 0; i < n; i++)
             {
                 ss[i] = res[i];
             }
             return(ss);
         }
     }
     return(null);
 }
Exemple #3
0
        static NicType TransMode = NicType.Direct; //默认为AT

        static void Main(string[] args)
        {
            foreach (string sss in args)
            {
                if (sss == "all")
                {
                    _serial_info    = false;
                    _pack_head_info = false;
                }
                else if (sss == "ser")
                {
                    _serial_info = false;
                }
                else if (sss == "packet")
                {
                    _pack_head_info = false;
                }
            }
            EnsureOnlyOneInstance();
            string conf_file = AppDomain.CurrentDomain.BaseDirectory + "config.ini";

            config.LoadIniFile(conf_file);
            config.SaveIniFile();


            string fileName  = (args.Length > 0) ? args[0] : Assembly.GetExecutingAssembly().Location;
            string buildtime = System.IO.File.GetLastWriteTime(fileName).ToString();
            string version   = "V0.4.0";
            string app_title = "HX Net Module (Universal) Emulate " + version + " build [" + buildtime + "]";

            ConsoleLogWriteLine(app_title);
            ConsoleLogWriteLine("==========================================================");

            FixRemoteIP = config.应用参数.使用固定IP.Trim() == "" ? false : true;
            if (FixRemoteIP)
            {
                Console.WriteLine("使用固定IP:" + config.应用参数.使用固定IP);
                rm_ip_fix = config.应用参数.使用固定IP;
            }
            else
            {
                Console.WriteLine("使用命令指定的IP, 如果没有指定便使用默认的:" + config.应用参数.使用固定IP);
            }

            //---------------------------------------------------------------------
            ser = new ComPort();
            ser.RecvTimeoutInMs = 1000;
            ConsoleLogWriteLine("Communication Configs:");
            //ConsoleLogWriteLine("Protocol : " + ser.DialogProcoto);
            // (ser.DialogProcoto == hxSerialProtocol.DialogProtocolType.SIMPLE?"SIMPLE":"UNIVERSAL") );
            ConsoleLogWriteLine("Baudrate : " + ser.Baudrate);
            ConsoleLogWriteLine("Recive Timeout : " + ser.RecvTimeoutInMs + "ms");
            //ConsoleLogWriteLine("Retry Times : " + ser.RetryTimes);

            ConsoleLogWriteLine("Alive Serial Ports:");
            List <uint> ap = new List <uint>();

            for (uint i = 0; i < 40; i++)
            {
                if (ser.Open(i))
                {
                    ser.Close();
                    ConsoleLogWriteLine("COM" + i);
                    ap.Add(i);
                }
            }
cfg_port_nr:
            ConsoleLogWrite("Please Select A Port :");
            string s = Console.ReadLine();
            uint   n;

            try { n = uint.Parse(s); }
            catch {
                ConsoleLogWriteLine("input error.");
                goto cfg_port_nr;
            }
            if (!ap.Contains(n))
            {
                ConsoleLogWriteLine("unalivable port.");
                goto cfg_port_nr;
            }
            if (!ser.Open(n))
            {
                ConsoleLogWriteLine("cannot open port.");
                goto cfg_port_nr;
            }
            ser.ShowData = _serial_info;
            ser.puts(app_title);
            try {
reset:
                ConsoleLogWriteLine("=====================================================================");
                ConsoleLogWriteLine("->Net Module Reset");
                Thread.Sleep(1000);
                ser.puts("+ZEND");

                for (;;)
                {
                    s = ser.gets();
                    s = s.Trim();
                    if (s.StartsWith("AT"))
                    {
                        bool dellf = false;
                        {
                            try {
                                string ss1 = config.应用参数.AT指令扩展匹配字符串;
                                if (ss1.Trim() == "")
                                {
                                    throw new System.Exception();
                                }
                                string[] sss1 = ss1.Split(new char[] { '|' });
                                if (sss1.Length < 2)
                                {
                                    throw new System.Exception();
                                }
                                for (int i = 0; i < sss1.Length; i += 2)
                                {
                                    if (s == sss1[i])
                                    {
                                        ser.puts(sss1[i + 1]);
                                        dellf = true;
                                    }
                                }
                            }
                            catch {
                            }

                            try {
                                string ss1 = config.应用参数.AT指令扩展起始指令匹配字符串;
                                if (ss1.Trim() == "")
                                {
                                    throw new System.Exception();
                                }
                                string[] sss1 = ss1.Split(new char[] { '|' });
                                if (sss1.Length < 2)
                                {
                                    throw new System.Exception();
                                }
                                for (int i = 0; i < sss1.Length; i += 2)
                                {
                                    if (s.StartsWith(sss1[i]))
                                    {
                                        dellf = true;
                                        ser.puts(sss1[i + 1]);
                                    }
                                }
                            }
                            catch { }

                            try {
                                string ss1 = config.应用参数.透传建立AT指令匹配起始;
                                if (ss1.Trim() == "")
                                {
                                    throw new System.Exception();
                                }
                                string[] sss1 = ss1.Split(new char[] { '|' });
                                if (sss1.Length < 1)
                                {
                                    throw new System.Exception();
                                }
                                if (s.StartsWith(sss1[0]))
                                {
                                    IPAddress ip   = IPAddress.Parse(rm_ip_fix);
                                    string    port = config.应用参数.使用固定端口;
                                    try {
                                        sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                        sock.Connect(new IPEndPoint(ip, int.Parse(port)));
                                        ser.puts("CONNECT");
                                        sock.BeginReceive(new byte[2048], 0, 2048, SocketFlags.None, new AsyncCallback(sock_recv_directly), ser);
                                        List <byte> buf  = new List <byte>();
                                        List <byte> buf9 = new List <byte>();
                                        buf.Clear();
                                        dellf = true;
                                        int tickcount = 0;
                                        for (;;)
                                        {
                                            try {
                                                //byte[] bs = ser.Recive(1024,100);
                                                //sock.Send(bs);
                                                //WriteLine("Dev->Server : (" + bs.Length + ") " + bin_to_asc(bs, bs.Length));
                                                //log.log("TX PACKET : " + bs.Length + " " + bin_to_asc(bs, bs.Length));

                                                byte[] bs = ser.Recive(1);
                                                if (bs != null && bs.Length == 1)
                                                {
                                                    byte b0 = bs[0];
                                                    if (b0 == '@')
                                                    {
                                                        tickcount = System.Environment.TickCount;
                                                        buf9.Clear();
                                                        buf.Clear();
                                                        buf.Add(b0);
                                                    }
                                                    else if (bs[0] == '#')
                                                    {
                                                        buf.Add(b0);
                                                        if (sock != null)
                                                        {
                                                            int nsend = sock.Send(buf.ToArray());
                                                            WriteLine("Dev->Server : (" + buf.Count + ") " + bin_to_asc(buf.ToArray(), buf.Count));
                                                            log.log("TX PACKET : " + buf.Count + " " + bin_to_asc(buf.ToArray(), buf.Count));
                                                        }
                                                        else
                                                        {
                                                            ser.puts("ERROR");
                                                        }
                                                        buf.Clear();
                                                    }
                                                    else
                                                    {
                                                        if (System.Environment.TickCount - tickcount > 500)
                                                        {
                                                            buf9.Add(b0);
                                                        }
                                                        if (buf9.Count > 2)
                                                        {
                                                            string   sss  = System.Text.Encoding.ASCII.GetString(buf9.ToArray());
                                                            string[] sas  = sss.Split(new string[] { "AT" }, StringSplitOptions.None);
                                                            string[] sas2 = sss.Split(new string[] { "\n" }, StringSplitOptions.None);
                                                            if (sas.Length > 3 && sas2.Length > 3)
                                                            {
                                                                try {
                                                                    sock.Shutdown(SocketShutdown.Both);
                                                                    sock.Close();
                                                                }
                                                                catch { }
                                                                goto reset;
                                                            }
                                                        }
                                                        if (buf.Count > 4096)
                                                        {
                                                            buf.Clear();
                                                        }
                                                        buf.Add(b0);
                                                    }
                                                }
                                            }
                                            catch {
                                                ;;;
                                            }
                                        }
                                    }
                                    catch {
                                    }
                                }
                                ser.puts(sss1[1]);
                            }


                            catch { }
                        }

                        if (dellf == false)
                        {
                            if (s == "AT")
                            {
                                ser.puts("AT");
                                ser.puts("OK");
                            }
                            else if (s == "ATE0")
                            {
                                ser.puts("ATE0");
                                ser.puts("OK");
                            }
                            else if (s == "ATE1")
                            {
                                ser.puts("OK");
                            }
                            else if (s == "AT+CSQ?")
                            {
                                ser.puts("OK");
                                ser.puts("+CSQ: 29,99");
                            }
                            else if (s == "AT+CREG?")
                            {
                                ser.puts("OK");
                                ser.puts("+REG: 1,1");
                            }
                            else if (s == "AT+CIPMODE=1")
                            {
                                ser.puts("OK");
                            }
                            else if (s == "AT+CIPSHUT")
                            {
                                ser.puts("SHUT OK");
                                ser.puts("OK");
                            }
                            else if (s.StartsWith("AT+CIPCSGP"))
                            {
                                ser.puts("OK");
                            }
                            else if (s.StartsWith("AT+CGSN"))
                            {
                                ser.puts("012345678901234");
                            }
                            else if (s.StartsWith("AT+CIMI"))
                            {
                                ser.puts("112233445566778");
                            }
                            else if (s.StartsWith("AT+ZIPCFG="))
                            {
                                ser.puts("OK");
                            }
                            else if (s.StartsWith("AT+ZIPCALL=1"))
                            {
                                ser.puts("OK");
                                ser.puts("+ZIPCALL: 1,99.88.99.88");
                            }
                            else if (s.StartsWith("AT+ZIPSTAT="))
                            {
                                int state = sock == null ? 0 : 1;
                                ser.puts("+ZIPSTAT: 1," + state);
                            }
                            else if (s.StartsWith("AT+CIPSTART"))
                            {
                                // "AT+CIPSTART="TCP","119.75.218.70","80"
                                try {
                                    string   v       = s.Split('=')[1];
                                    string[] ss      = v.Split(',');
                                    string   ip_addr = ss[1].Trim(new char[] { '\"' });
                                    string   port    = ss[2].Trim(new char[] { '\"' });
                                    if (ip_addr != null && port != null)
                                    {
                                        ser.puts("OK");

                                        IPAddress ip;
                                        if (FixRemoteIP)
                                        {
                                            ip = IPAddress.Parse(rm_ip_fix);
                                        }
                                        else
                                        {
                                            ip = IPAddress.Parse(ip_addr);
                                        }
                                        try {
                                            sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                            sock.Connect(new IPEndPoint(ip, int.Parse(port)));
                                            //byte[] bbb = new byte[1024];
                                            //int nnn = sock.Receive(bbb);
                                            ser.puts("CONNECT");
                                            sock.BeginReceive(new byte[2048], 0, 2048, SocketFlags.None, new AsyncCallback(sock_recv_directly), ser);
                                            List <byte> buf  = new List <byte>();
                                            List <byte> buf9 = new List <byte>();
                                            buf.Clear();
                                            int tickcount = 0;
                                            for (;;)
                                            {
                                                try {
                                                    //byte[] bs = ser.Recive(1024,100);
                                                    //sock.Send(bs);
                                                    //WriteLine("Dev->Server : (" + bs.Length + ") " + bin_to_asc(bs, bs.Length));
                                                    //log.log("TX PACKET : " + bs.Length + " " + bin_to_asc(bs, bs.Length));

                                                    byte[] bs = ser.Recive(1);
                                                    if (bs != null && bs.Length == 1)
                                                    {
                                                        byte b0 = bs[0];
                                                        if (b0 == '@')
                                                        {
                                                            tickcount = System.Environment.TickCount;
                                                            buf9.Clear();
                                                            buf.Clear();
                                                            buf.Add(b0);
                                                        }
                                                        else if (bs[0] == '#')
                                                        {
                                                            buf.Add(b0);
                                                            if (sock != null)
                                                            {
                                                                int nsend = sock.Send(buf.ToArray());
                                                                WriteLine("Dev->Server : (" + buf.Count + ") " + bin_to_asc(buf.ToArray(), buf.Count));
                                                                log.log("TX PACKET : " + buf.Count + " " + bin_to_asc(buf.ToArray(), buf.Count));
                                                            }
                                                            else
                                                            {
                                                                ser.puts("ERROR");
                                                            }
                                                            buf.Clear();
                                                        }
                                                        else
                                                        {
                                                            if (System.Environment.TickCount - tickcount > 500)
                                                            {
                                                                buf9.Add(b0);
                                                            }
                                                            if (buf9.Count >= 3)
                                                            {
                                                                if (buf9[0] == '+' &&
                                                                    buf9[1] == '+' &&
                                                                    buf9[2] == '+')
                                                                {
                                                                    sock.Shutdown(SocketShutdown.Both);
                                                                    sock.Close();
                                                                    ser.puts("OK");
                                                                    WriteLine("+++ DISCONNECT");
                                                                    log.log("+++ DISCONNECT");
                                                                    goto reset;
                                                                }
                                                            }
                                                            if (buf9.Count > 2)
                                                            {
                                                                string   sss  = System.Text.Encoding.ASCII.GetString(buf9.ToArray());
                                                                string[] sas  = sss.Split(new string[] { "AT" }, StringSplitOptions.None);
                                                                string[] sas2 = sss.Split(new string[] { "\n" }, StringSplitOptions.None);
                                                                if (sas.Length > 3 && sas2.Length > 3)
                                                                {
                                                                    try {
                                                                        sock.Shutdown(SocketShutdown.Both);
                                                                        sock.Close();
                                                                    }
                                                                    catch { }
                                                                    goto reset;
                                                                }
                                                            }
                                                            if (buf.Count > 4096)
                                                            {
                                                                buf.Clear();
                                                            }
                                                            buf.Add(b0);
                                                        }
                                                    }
                                                }
                                                catch {
                                                    ;;;
                                                }
                                            }
                                        }
                                        catch {
                                        }
                                    }
                                }

                                catch {
                                }
                                ser.puts("ERROR");
                            }
                            else if (s.StartsWith("AT+ZIPSEND="))
                            {
                                string   v        = s.Split('=')[1];
                                string[] ss       = v.Split(',');
                                string   sock_id  = ss[0];
                                string   data     = ss[1];
                                byte[]   bin_data = asc_to_bin(data);
                                AnalysPacket(1, data);
                                ser.puts("OK");
                                if (sock != null)
                                {
                                    int nsend = sock.Send(bin_data);
                                    ser.puts("+ZIPSEND:1," + nsend);
                                    log.log("TX PACKET : " + data);
                                }
                                else
                                {
                                    ser.puts("ERROR");
                                }
                            }
                            else if (s.StartsWith("AT+ZIPOPEN="))
                            {
                                string   v          = s.Split('=')[1];
                                string[] ss         = v.Split(',');
                                string   sock_id    = ss[0];
                                string   tcp0_udp1  = ss[1];
                                string   ip_addr    = ss[2];
                                string   port       = ss[3];
                                string   local_port = ss[4];
                                ser.puts("OK");

                                IPAddress ip;
                                if (FixRemoteIP)
                                {
                                    port = config.应用参数.使用固定端口;
                                    ip   = IPAddress.Parse(rm_ip_fix);
                                }
                                else
                                {
                                    ip = IPAddress.Parse(ip_addr);
                                }
                                try {
                                    sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                    sock.Connect(new IPEndPoint(ip, int.Parse(port)));
                                    ser.puts("+ZIPSTAT: " + sock_id + "," + 1);

                                    sock.BeginReceive(new byte[2048], 0, 2048, SocketFlags.None, new AsyncCallback(sock_recv), ser);
                                }
                                catch {
                                    ser.puts("+ZIPSTAT: " + sock_id + "," + 0);
                                }
                            }
                            else
                            {
                                ser.puts("***ERROR");
                            }
                        }
                    }
                    else if (s.StartsWith("TK"))
                    {
                        if (s == "TK+RESET")
                        {
                            ser.puts("OK");
                            goto reset;
                        }
                    }
                    else
                    {
                    }
                }
            }
            catch {
            }

            System.Console.ReadKey();
        }