Ejemplo n.º 1
0
        // POST: api/TCP_SendReceiveByte
        public string Post(classTcpConnect value)
        {
            try
            {
                gnSqlNomal gn     = new gnSqlNomal();
                var        config = gn.convertConfigToDic(value.config);
                var        para   = gn.convertParaToDic(value.para);


                // Data buffer for incoming data.
                byte[] bytes    = new byte[1024];
                var    item     = _cachSocket.GetCacheItem(config["keysocket"]);
                Socket socketCa = null;
                if (item != null)
                {
                    socketCa = item.Value as Socket;
                }
                // Connect to a remote device.
                if (config["typecommand"] == "connect")
                {
                    try
                    {
                        IPAddress  ipAddress = IPAddress.Parse(para["ip"]);
                        IPEndPoint remoteEP  = new IPEndPoint(ipAddress, Convert.ToInt32(para["port"]));
                        // Create a TCP/IP  socket.
                        Socket sender = new Socket(AddressFamily.InterNetwork,
                                                   SocketType.Stream, ProtocolType.Tcp);
                        // Connect the socket to the remote endpoint. Catch any errors.
                        sender.ReceiveTimeout = 10000;
                        sender.SendTimeout    = 10000;

                        sender.Connect(remoteEP);

                        List <string> cacheKeys = MemoryCache.Default.Select(kvp => kvp.Key).ToList();
                        foreach (string cacheKey in cacheKeys)
                        {
                            if (cacheKey == config["keysocket"])
                            {
                                MemoryCache.Default.Remove(cacheKey);
                            }
                        }

                        _cachSocket.Add(config["keysocket"], sender, DateTime.Now.AddHours(2));
                        //  return "{\"result\":\"OK\",\"data\":[{\"status\":\"OK\"}]}";
                        // }

                        return("OK");
                    }

                    catch (Exception ex)
                    {
                        return(ex.Message);
                    }
                }

                if (config["typecommand"] == "sendbyte" && _cachSocket.Contains(config["keysocket"]))
                {
                    try
                    {
                        // Send the data through the socket.
                        general gns      = new general();
                        var     sendbyte = gns.HexToByteArray(para["lenh"]);
                        socketCa.Send(sendbyte);
                        return("OK");
                    }
                    catch (Exception ex)
                    {
                        return(ex.Message);
                    }
                }
                if (config["typecommand"] == "receivebyte")
                {
                    try
                    {
                        socketCa.ReceiveTimeout = 50;

                        int bytesRec = socketCa.Receive(bytes);
                        var data     = bytes.ToList().GetRange(0, bytesRec).ToArray();
                        return(BitConverter.ToString(data));
                    }
                    catch (Exception ex)
                    {
                        return("");
                    }
                }

                //// Release the socket.
                if (config["typecommand"] == "disconnect")
                {
                    try
                    {
                        // Receive the response from the remote device.

                        socketCa.Dispose();
                        socketCa.Close();
                        return("OK");
                    }
                    catch (Exception ex)
                    {
                        return("{\"result\":\"ERROR\",\"data\":[]}");
                    }
                }
                return("Kiểm tra lại lệnh không đúng định dạng");
            }
            catch (Exception ex) { return(ex.Message); }
        }
        // POST: api/TCP_SendReceiveByte232
        public string Post(classTcpConnect value)
        {
            try
            {
                Socket     sender = null;
                gnSqlNomal gn     = new gnSqlNomal();
                var        config = gn.convertConfigToDic(value.config);
                var        para   = gn.convertParaToDic(value.para);

                // Data buffer for incoming data.
                byte[] bytes = new byte[1024];

                try
                {
                    IPAddress  ipAddress = IPAddress.Parse(para["ip"]);
                    IPEndPoint remoteEP  = new IPEndPoint(ipAddress, Convert.ToInt32(para["port"]));
                    // Create a TCP/IP  socket.
                    sender = new Socket(AddressFamily.InterNetwork,
                                        SocketType.Stream, ProtocolType.Tcp);
                    // Connect the socket to the remote endpoint. Catch any errors.
                    sender.Connect(remoteEP);
                }
                catch (Exception ex)
                {
                    return("{\"result\":\"ERROR\",\"data\":[{\"status\":\"" + ex.Message + "\"}]}");
                }
                var v_lenh = config["lenh"];
                try
                {
                    // Send các lệnh connect mặc định
                    sender.Send(Encoding.ASCII.GetBytes("#0000000000000009+CSQ:IFCMASTER#"));
                    Thread.Sleep(500);
                    string imei = config["keysocket"];
                    sender.Send(Encoding.ASCII.GetBytes("@READ" + imei));
                    Thread.Sleep(500);


                    // Send the data through the socket.
                    general gns       = new general();
                    var     sendbyte  = gns.HexToByteArray(config["lenh"]);
                    int     bytesSent = sender.Send(sendbyte);

                    // Tao file log de view
                    try
                    {
                        var    dicAppSet = gns.ReadAppseting();
                        string path      = dicAppSet["pathlogcommandstreetlight"];
                        string filename  = path + config["namefile"] + "_" + DateTime.Now.ToString("ddMMyyHHmmss") + ".txt";
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        if (!File.Exists(filename))
                        {
                            // Create a file to write to.
                            using (StreamWriter sw = File.CreateText(filename))
                            {
                                //sw.WriteLine(para["ip"]);
                                //sw.WriteLine(para["port"]);
                                sw.WriteLine(BitConverter.ToString(sendbyte));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
                catch (Exception ex)
                {
                    return("{\"result\":\"ERROR\",\"data\":[{\"status\":\"" + ex.Message + "\"}]}");
                }

                // Release the socket.
                try
                {
                    // Receive the response from the remote device.
                    var shutdown  = Encoding.ASCII.GetBytes("shutdown");
                    int bytesSent = sender.Send(shutdown);

                    //_dicSocket[config["keysocket"]].Shutdown(SocketShutdown.Both);
                    //_dicSocket[config["keysocket"]].Close();
                    return("{\"result\":\"OK\",\"data\":" + v_lenh + "}");
                }
                catch (Exception ex)
                {
                    return("{\"result\":\"ERROR\",\"data\":[{\"status\":\"" + ex.Message + "\"}]}");
                }
            }
            catch (Exception ex) { return("{\"result\":\"ERROR\",\"data\":[{\"status\":\"" + ex.Message + "\"}]}"); }
        }