// POST: api/TCP_OverServiceTcp public string Post(classTcpByte value) { try { gnSqlNomal gn = new gnSqlNomal(); general gns = new general(); var dicAppSet = gns.ReadAppseting(); if (value == null || value.config == null) { return(null); } var config = gn.convertConfigToDic(value.config); var para = gn.convertParaToDic(value.para); var str = ""; foreach (var val in para) { if (val.Key != "data" && para["type"] == "sendbyte") { str += val.Value + "\r\n"; } if (val.Key == "data" && para["type"] == "sendbyte") { var arr = val.Value.Replace("\r\n", "").Replace(" ", "").Replace("[", "").Replace("]", "").Replace("\"", "").Split(','); var lstss = new List <byte>(); foreach (var dataa in arr) { var bytes = gns.HexToByteArray(dataa); lstss.AddRange(bytes); } //var thu = System.Text.ASCIIEncoding.ASCII.GetBytes("#0000000000000009+CSQ:IFCMASTER#"); // var thu1 = BitConverter.to "#0000000000000009+CSQ:IFCMASTER#"; str += BitConverter.ToString(lstss.ToArray()) + "\r\n"; } } File.WriteAllText(dicAppSet["pathfoldertcpsend"] + config["namefile"], str); var result = ""; if (para["type"].ToLower() == "checkconnect" || para["type"].ToLower() == "receive") { var pathReceive = dicAppSet["pathfoldertcpreceive"] + config["namefile"]; if (File.Exists(pathReceive)) { result = File.ReadAllText(pathReceive); //var bytes = Array.ConvertAll<string, byte>(resultByte.Substring(0, resultByte.Length-1).Split('-'), s => Convert.ToByte(s, 16)); //StringBuilder sb = new StringBuilder(bytes.Length * 2); //foreach (byte b in bytes) //{ // sb.AppendFormat("{0:x2}", b); //} //result = sb.ToString(); File.Delete(pathReceive); } else { return(""); } } return(result); } catch (Exception ex) { return(ex.Message); } }
// 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 + "\"}]}"); } }