using System; using System.Collections.Generic; using System.Data; using System.Dynamic; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Threading; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UAS_MES_NEW.DataOperate; using UAS_MES_NEW.Entity; namespace UAS_MES_NEW.PublicMethod { public class BindItem { [JsonProperty("bindKey")] public string BindKey { get; set; } [JsonProperty("bindValue")] public string BindValue { get; set; } [JsonProperty("keyType")] public string KeyType { get; set; } [JsonProperty("keyValue")] public string KeyValue { get; set; } [JsonProperty("hashType")] public string HashType { get; set; } [JsonProperty("hashKey")] public string HashKey { get; set; } } public class RootObject { [JsonProperty("productModuleType")] public string ProductModuleType { get; set; } [JsonProperty("productMainClass")] public string ProductMainClass { get; set; } [JsonProperty("productMediumClass")] public string ProductMediumClass { get; set; } [JsonProperty("productSubClass")] public string ProductSubClass { get; set; } [JsonProperty("task")] public string Task { get; set; } [JsonProperty("processType")] public string ProcessType { get; set; } [JsonProperty("userId")] public string UserId { get; set; } [JsonProperty("bindList")] public List BindList { get; set; } } public class DeviceInfo { [JsonProperty("tool_name")] public string ToolName { get; set; } [JsonProperty("response")] public string Response { get; set; } [JsonProperty("status")] public int Status { get; set; } [JsonProperty("product_name")] public string ProductName { get; set; } [JsonProperty("product_mode")] public string ProductMode { get; set; } [JsonProperty("material_code")] public string MaterialCode { get; set; } [JsonProperty("batch_no")] public string BatchNo { get; set; } [JsonProperty("production_date")] public string ProductionDate { get; set; } [JsonProperty("big_box_no")] public string BigBoxNo { get; set; } [JsonProperty("box_no")] public string BoxNo { get; set; } [JsonProperty("reserve10")] public string Reserve10 { get; set; } [JsonProperty("packing_num")] public int PackingNum { get; set; } [JsonProperty("soft_version")] public string SoftVersion { get; set; } [JsonProperty("hd_version")] public string HdVersion { get; set; } [JsonProperty("voltage")] public string Voltage { get; set; } [JsonProperty("power")] public string Power { get; set; } [JsonProperty("order_no")] public string OrderNo { get; set; } // 使用字典或列表来存储序列化的数组数据 public List DSN { get; set; } = new List(); public List MacStart { get; set; } = new List(); public List MacEnd { get; set; } = new List(); public List DeviceId { get; set; } = new List(); public List DevEnNo { get; set; } = new List(); public List Reserve3 { get; set; } = new List(); public List Reserve4 { get; set; } = new List(); } public class DeviceInfoConverter : JsonConverter { public override DeviceInfo ReadJson(JsonReader reader, System.Type objectType, DeviceInfo existingValue, bool hasExistingValue, JsonSerializer serializer) { JObject jsonObject = JObject.Load(reader); DeviceInfo deviceInfo = new DeviceInfo(); // 解析基本字段 serializer.Populate(jsonObject.CreateReader(), deviceInfo); // 解析数组字段 ParseArrayFields(jsonObject, deviceInfo); return deviceInfo; } public override void WriteJson(JsonWriter writer, DeviceInfo value, JsonSerializer serializer) { throw new NotImplementedException(); } private void ParseArrayFields(JObject jsonObject, DeviceInfo deviceInfo) { int index = 0; // 解析 d_sn 数组 while (true) { string key = $"d_sn{index}"; if (jsonObject.TryGetValue(key, out JToken value)) { deviceInfo.DSN.Add(value.ToString()); index++; } else { break; } } // 解析 mac_start 数组 index = 0; while (true) { string key = $"mac_start{index}"; if (jsonObject.TryGetValue(key, out JToken value)) { deviceInfo.MacStart.Add(value.ToString()); index++; } else { break; } } // 解析 mac_end 数组 index = 0; while (true) { string key = $"mac_end{index}"; if (jsonObject.TryGetValue(key, out JToken value)) { deviceInfo.MacEnd.Add(value.ToString()); index++; } else { break; } } // 解析 dev_en_no 数组 index = 0; while (true) { string key = $"dev_en_no{index}"; if (jsonObject.TryGetValue(key, out JToken value)) { deviceInfo.DevEnNo.Add(value.ToString()); index++; } else { break; } } // 解析 reserve3 数组 index = 0; while (true) { string key = $"reserve3_{index}"; if (jsonObject.TryGetValue(key, out JToken value)) { deviceInfo.Reserve3.Add(value.ToString()); index++; } else { break; } } // 解析 reserve4 数组 index = 0; while (true) { string key = $"reserve4_{index}"; if (jsonObject.TryGetValue(key, out JToken value)) { deviceInfo.Reserve4.Add(value.ToString()); index++; } else { break; } } // 解析 DeviceId 数组 index = 0; while (true) { string key = $"DeviceId{index}"; if (jsonObject.TryGetValue(key, out JToken value)) { deviceInfo.DeviceId.Add(value.ToString()); index++; } else { break; } } } } public class HttpServer { static DataHelper dh = new DataHelper(); public static int SN_SERVICE_PORT = 8234; public static int MAX_BUF_SIZE = 4096; static string ComputeSha256Hash(string input) { using (SHA256 sha256 = SHA256.Create()) { byte[] bytes = Encoding.UTF8.GetBytes(input); byte[] hashBytes = sha256.ComputeHash(bytes); StringBuilder builder = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { builder.Append(hashBytes[i].ToString("x2")); } return builder.ToString().ToUpper(); } } //获取SN的EN号,彩盒标机身标一个工站一起打印,需要SN单个获取 public static void GetEN(string iSN) { DataTable dt = (DataTable)dh.ExecuteSql("select ms_makecode,pr_prefix,pr_prebigxbox,pr_regcode from makeserial left join product on ms_prodcode=pr_code where ms_sncode ='" + iSN + "' order by ms_id desc", "select"); string prefix = ""; string regcode = ""; string makecode = ""; if (dt.Rows.Count > 0) { prefix = dt.Rows[0]["pr_prefix"].ToString(); regcode = dt.Rows[0]["pr_regcode"].ToString(); makecode = dt.Rows[0]["ms_makecode"].ToString(); } dynamic obj = new ExpandoObject(); obj.tool_name = "zte"; obj.request = "Storage2"; obj.User = "mes"; obj.password = "258456"; obj.po_sn = iSN; obj.wholeDeviceCode = ""; obj.reg_code = regcode; obj.prefix_en_no = prefix; obj.prefix_big_box = ""; obj.packing_num = ""; obj.isn = prefix; string json = JsonConvert.SerializeObject(obj, Formatting.Indented); string returnstr = SendData(json); JObject deviceObj = JObject.Parse(returnstr); string WholeDeviceCode = deviceObj["WholeDeviceCode"].ToString(); string SN = deviceObj["SN"].ToString(); string dev_en_no = deviceObj["dev_en_no"].ToString(); string mac = deviceObj["mac"].ToString(); string mac_start = deviceObj["mac_start"].ToString(); string mac_end = deviceObj["mac_end"].ToString(); string reg_code = deviceObj["reg_code"].ToString(); string reserve3 = deviceObj["reserve3"].ToString(); string device_type = deviceObj["device_type"].ToString(); string en_no = deviceObj["en_no"].ToString(); dh.ExecuteSql("insert into ZTEDATA(ZD_ID,ZD_D_SN,zd_WholeDeviceCode,ZD_DEV_EN_NO,ZD_SN, ZD_MAKECODE, ZD_TYPE, ZD_VALUE,zd_mac,ZD_MAC_START, ZD_MAC_END,ZD_RESERVE3,zd_enno,zd_devicetype,zd_regcode)" + "values(ZTEDATA_seq.nextval,'" + SN + "','" + WholeDeviceCode + "','" + dev_en_no + "','" + iSN + "','" + makecode + "','彩盒机身标','','" + mac + "','" + mac_start + "','" + mac_end + "','" + reserve3 + "','" + en_no + "','" + device_type + "','" + reg_code + "')", "insert"); Console.WriteLine(json); } //发送外箱号数据,打印前获取 public static void SendBoxData(string iBox) { string sn = dh.getFieldDataByCondition("packagedetail", "replace(wm_concat(pd_barcode),',','-')", "pd_outboxcode='" + iBox + "'").ToString(); DataTable dt = (DataTable)dh.ExecuteSql("select pr_custmachinetype,ms_makecode from makeserial left join product on ms_prodcode=pr_code where ms_outboxcode ='" + iBox + "' order by ms_id desc", "select"); string pr_custmachinetype = ""; string makecode = ""; if (dt.Rows.Count > 0) { pr_custmachinetype = dt.Rows[0]["pr_custmachinetype"].ToString(); makecode = dt.Rows[0]["ms_makecode"].ToString(); } var root = new RootObject { ProductModuleType = "整机", ProductMainClass = "固网_CPE", ProductMediumClass = "CPE", ProductSubClass = pr_custmachinetype, Task = makecode, ProcessType = "生产过程", UserId = User.UserName, BindList = new List() }; root.BindList.Add(new BindItem { BindKey = "cartonSn", BindValue = iBox, KeyType = "macbox", KeyValue = sn, HashType = "SHA256", HashKey = ComputeSha256Hash(sn) }); dt = (DataTable)dh.ExecuteSql("select pd_barcode from packagedetail pd_outboxcode='" + iBox + "'", "select"); for (int i = 0; i < dt.Rows.Count; i++) { root.BindList.Add(new BindItem { BindKey = "mac", BindValue = dt.Rows[i]["pd_barcode"].ToString(), KeyType = "EN", KeyValue = "4Y12R9300001", HashType = "NON-HASH", HashKey = "4Y12R9300001" }); root.BindList.Add(new BindItem { BindKey = "mac", BindValue = dt.Rows[i]["pd_barcode"].ToString(), KeyType = "电源条码", KeyValue = "1U1Y2505100013640", HashType = "NON-HASH", HashKey = "1U1Y2505100013640" }); root.BindList.Add(new BindItem { BindKey = "mac", BindValue = dt.Rows[i]["pd_barcode"].ToString(), KeyType = "JY-License", KeyValue = "Qk1K4rmuowTDl+NEtSIeHx1td6Tzzm0wDrw/AMCvJ6mrXQ5wsSgoxia+T5Cj+uH4xrGUrjGrZvh/WUQN88iDrPO7kuTA0mvo/Ay+AsFJYnn00JQYQkN9ul+a+Qh0EPBqCVa4ikllHcD1Pqq4Eubs6XXNFhKOtK7F7FMotfGzzAVg7RhKVoVRVFcK6ubSVWXW+SnGx5muH+WZPaiHLjt+kxBR8tZJuBl1LQvMWP74JSWKkcFWwcWlARnCJePvRTvKTDd5e7q9rpBpAc7Z79XYQ6Fs4eXM44O6/hA88YW/BK0TZq3AaaMxH8BpJnwZt4lIyuqXispeaB2eieFBR0JwWg==", HashType = "SHA256", HashKey = ComputeSha256Hash(sn), }); ; } string json = JsonConvert.SerializeObject(root, Formatting.Indented); string returnstr = SendData(json); Console.WriteLine(json); } //获取外箱号信息 public static void GetOutBoxInfo(string iBox) { dynamic obj = new ExpandoObject(); var expandoDict = obj as IDictionary; DataTable dt = (DataTable)dh.ExecuteSql("select pd_barcode,pd_makecode from packagedetail where pd_outboxcode='" + iBox + "'", "select"); string makecode = ""; for (int i = 0; i < dt.Rows.Count; i++) { string enNoKey = $"en_no{i}"; string enNoValue = dt.Rows[i]["pd_barcode"].ToString(); expandoDict[enNoKey] = enNoValue; makecode = dt.Rows[i]["pd_makecode"].ToString(); } obj.request = "Q_wai_xiang"; obj.packing_num = 20; obj.User = "mes"; obj.po_sn = makecode; obj.password = "258456"; obj.tool_name = "zte"; obj.noType = 0; string json = JsonConvert.SerializeObject(obj, Formatting.Indented); string returnstr = SendData(json); var settings = new JsonSerializerSettings { Converters = new List { new DeviceInfoConverter() } }; DeviceInfo deviceInfo = JsonConvert.DeserializeObject(returnstr, settings); for (int i = 0; i < deviceInfo.DSN.Count; i++) { Console.WriteLine($"设备 {i}:"); Console.WriteLine($" 序列号: {deviceInfo.DSN[i]}"); Console.WriteLine($" MAC起始: {deviceInfo.MacStart[i]}"); Console.WriteLine($" MAC结束: {deviceInfo.MacEnd[i]}"); Console.WriteLine($" 设备编码: {deviceInfo.DevEnNo[i]}"); Console.WriteLine($" 预留3: {deviceInfo.Reserve3[i]}"); } //将返回的信息存入数据库 for (int i = 0; i < deviceInfo.DSN.Count; i++) { dh.ExecuteSql("insert into ZTEDATA(ZD_ID,ZD_SN, ZD_MAKECODE, ZD_TYPE, ZD_VALUE,ZD_product_mode, ZD_PRODUCTNAME, ZD_MATERIAL_CODE, ZD_BATCH_NO, ZD_SOFT_VERSION, ZD_HD_VERSION, " + "ZD_VOLTAGE, ZD_POWER, ZD_ORDER_NO, ZD_BIG_BOX_NO, ZD_D_SN, ZD_DEV_EN_NO, ZD_RESERVE3, ZD_DEVICEID, ZD_MAC_START, ZD_MAC_END,zd_production_date, ZD_INDATE)" + "values(ZTEDATA_seq.nextval,'" + deviceInfo.DSN[i] + "','','BOX','','" + deviceInfo.ProductName + "','" + deviceInfo.ProductName + "','" + deviceInfo.MaterialCode + "','" + deviceInfo.BatchNo + "','" + deviceInfo.SoftVersion + "','" + deviceInfo.HdVersion + "'," + "'" + deviceInfo.Voltage + "','" + deviceInfo.Power + "','" + deviceInfo.OrderNo + "','" + deviceInfo.BigBoxNo + "','" + deviceInfo.DSN[i] + "'," + "'" + deviceInfo.Reserve3[i] + "','" + deviceInfo.DeviceId[i] + "','" + deviceInfo.MacStart[i] + "','" + deviceInfo.MacEnd[i] + "','" + deviceInfo.ProductionDate + "',sysdate)", "insert"); } Console.WriteLine(json); } //获取栈板信息 public static void GetPalletInfo(string iBox) { DataTable dt = (DataTable)dh.ExecuteSql("select pa_outboxcode,pa_makecode from package where pa_mothercode='" + iBox + "'", "select"); dynamic obj = new ExpandoObject(); var expandoDict = obj as IDictionary; string makecode = ""; for (int i = 0; i < dt.Rows.Count; i++) { string enNoKey = $"big_box_no{i}"; string enNoValue = dt.Rows[i]["pa_outboxcode"].ToString(); expandoDict[enNoKey] = enNoValue; makecode = dt.Rows[i]["pa_makecode"].ToString(); } obj.request = "pallet"; obj.packing_num = dt.Rows.Count; obj.User = "mes"; obj.po_sn = makecode; obj.password = "258456"; obj.tool_name = "zte"; string json = JsonConvert.SerializeObject(obj, Formatting.Indented); string returnstr = SendData(json); Console.WriteLine(returnstr); Console.WriteLine(json); } //发送数据 public static string SendData(string json) { string serverIP = "10.1.162.175"; int port = 8234; try { TcpClient client = new TcpClient(); client.Connect(serverIP, port); NetworkStream stream = client.GetStream(); // 发送数据 byte[] data = Encoding.UTF8.GetBytes(json); stream.Write(data, 0, data.Length); Console.WriteLine($"已发送请求: {json}"); // 接收响应 - 使用安全的方式 return ReceiveDataSafely(stream); } catch (Exception ex) { Console.WriteLine($"错误: {ex.Message}"); return ""; } } private static string ReceiveDataSafely(NetworkStream stream) { MemoryStream ms = new MemoryStream(); byte[] buffer = new byte[1024]; int totalBytesRead = 0; const int MAX_SIZE = 10 * 1024 * 1024; try { stream.ReadTimeout = 5000; while (true) { int bytesRead = stream.Read(buffer, 0, buffer.Length); if (bytesRead == 0) break; ms.Write(buffer, 0, bytesRead); totalBytesRead += bytesRead; Console.WriteLine($"本次读取: {bytesRead} 字节, 累计: {totalBytesRead} 字节"); if (totalBytesRead > MAX_SIZE) { throw new Exception($"接收数据超过大小限制: {MAX_SIZE} 字节"); } if (!stream.DataAvailable) { Thread.Sleep(100); if (!stream.DataAvailable) break; } } byte[] receivedData = ms.ToArray(); // 直接使用GBK编码(最常用的中文编码) Encoding chineseEncoding = Encoding.GetEncoding("GBK"); string response = chineseEncoding.GetString(receivedData); Console.WriteLine($"使用GBK编码的响应: {response}"); return response; } catch (TimeoutException) { byte[] partialData = ms.ToArray(); Encoding chineseEncoding = Encoding.GetEncoding("GBK"); string partialResponse = chineseEncoding.GetString(partialData); Console.WriteLine($"接收超时,已接收数据: {partialResponse}"); return partialResponse; } } public static readonly uint PROTOCOL_FLAG = 0x4C4F4F54; public static byte[] BuildPacket(string jsonData) { if (string.IsNullOrEmpty(jsonData)) { throw new ArgumentException("JSON数据不能为空"); } using (MemoryStream ms = new MemoryStream()) { // 1. 写入flag (小端序) byte[] flagBytes = BitConverter.GetBytes(PROTOCOL_FLAG); ms.Write(flagBytes, 0, 4); // 2. 将JSON字符串转换为UTF8字节数组 byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonData); // 3. 写入data_len (小端序) byte[] lengthBytes = BitConverter.GetBytes(jsonBytes.Length); ms.Write(lengthBytes, 0, 4); // 4. 写入data ms.Write(jsonBytes, 0, jsonBytes.Length); return ms.ToArray(); } } public static string ToServerReq(string strJSON) { int nRet = 0; string strServerIP = "10.1.162.175"; string strResp = ""; IPAddress ip = IPAddress.Parse(strServerIP); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); while (true) { try { clientSocket.Connect(new IPEndPoint(ip, SN_SERVICE_PORT)); } catch { nRet = -13; break; } try { FACT_DATA_HEAD stHead = new FACT_DATA_HEAD(null); byte[] bytJson = Encoding.UTF8.GetBytes(strJSON); //Encoding.ASCII.GetBytes(strJSON); stHead.setDataLen(bytJson.Length); byte[] bytBuf = new byte[FACT_DATA_HEAD.MY_LEN + bytJson.Length]; byte[] bytSrcHead = stHead.getBytes(); Array.Copy(bytSrcHead, 0, bytBuf, 0, bytSrcHead.Length); Array.Copy(bytJson, 0, bytBuf, FACT_DATA_HEAD.MY_LEN, bytJson.Length); clientSocket.Send(bytBuf); } catch { nRet = -12; break; } //判定接口回传的flag和本地传过去的是否一致 byte[] bytRecv = new byte[MAX_BUF_SIZE]; int nRecvSize = 0, nSize = 0; nRecvSize = clientSocket.Receive(bytRecv, 0, FACT_DATA_HEAD.MY_LEN, SocketFlags.None); // string strTmp; // strTmp = string.Format("clientSocket.Receive={0}", nRecvSize); // Trace.WriteLine(strTmp); if (nRecvSize > 0) { FACT_DATA_HEAD stHead = new FACT_DATA_HEAD(bytRecv); Console.WriteLine(stHead.getFlag()); Console.WriteLine(FACT_DATA_HEAD.PROTOCOL_FLAG); if (stHead.getFlag() == FACT_DATA_HEAD.PROTOCOL_FLAG) { int nPos = 0; nSize = stHead.getDatalen(); while (nPos < nSize) { nRecvSize = clientSocket.Receive(bytRecv, nPos, 1869881979 - nPos, SocketFlags.None); if (nRecvSize < 0) { nRet = -14; break; } nPos += nRecvSize; } strResp = Encoding.Default.GetString(bytRecv, 0, nSize); } else nRet = -11; } else nRet = -10; break; } if (nRet > -13) clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); return strResp; } } }