Sfoglia il codice sorgente

修改外箱数据解析

callm 1 mese fa
parent
commit
6b35d6ce7e
1 ha cambiato i file con 273 aggiunte e 66 eliminazioni
  1. 273 66
      UAS_MES_HYSX/PublicMethod/HttpServer.cs

+ 273 - 66
UAS_MES_HYSX/PublicMethod/HttpServer.cs

@@ -7,6 +7,7 @@ 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;
@@ -15,7 +16,6 @@ using UAS_MES_NEW.Entity;
 namespace UAS_MES_NEW.PublicMethod
 {
 
-
     public class BindItem
     {
         [JsonProperty("bindKey")]
@@ -63,35 +63,208 @@ namespace UAS_MES_NEW.PublicMethod
         [JsonProperty("bindList")]
         public List<BindItem> BindList { get; set; }
     }
-    public class ZteData
+    public class DeviceInfo
     {
-        public string tool_name { get; set; }
-        public string response { get; set; }
-        public int status { get; set; }
-        public string product_name { get; set; }
-        public string product_mode { get; set; }
-        public string material_code { get; set; }
-        public string batch_no { get; set; }
-        public string production_date { get; set; }
-        public string big_box_no { get; set; }
-        public string box_no { get; set; }
-        public string reserve10 { get; set; }
-        public int packing_num { get; set; }
-        public string soft_version { get; set; }
-        public string hd_version { get; set; }
-        public string voltage { get; set; }
-        public string power { get; set; }
-        public string order_no { get; set; }
-        public string[] d_sn { get; set; }
-        public string[] mac_start { get; set; }
-        public string[] mac_end { get; set; }
-        public string[] DeviceId { get; set; }
-        public string[] dev_en_no { get; set; }
-        public string[] reserve3 { get; set; }
-        public string[] reserve4 { get; set; }
+        [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<string> DSN { get; set; } = new List<string>();
+        public List<string> MacStart { get; set; } = new List<string>();
+        public List<string> MacEnd { get; set; } = new List<string>();
+        public List<string> DeviceId { get; set; } = new List<string>();
+        public List<string> DevEnNo { get; set; } = new List<string>();
+        public List<string> Reserve3 { get; set; } = new List<string>();
+        public List<string> Reserve4 { get; set; } = new List<string>();
     }
+    public class DeviceInfoConverter : JsonConverter<DeviceInfo>
+    {
+        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;
+                }
+            }
 
-    class HttpServer
+            // 解析 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;
@@ -251,15 +424,31 @@ namespace UAS_MES_NEW.PublicMethod
 
             string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
             string returnstr = SendData(json);
-            ZteData zteData = JsonConvert.DeserializeObject<ZteData>(returnstr);
+
+            var settings = new JsonSerializerSettings
+            {
+                Converters = new List<JsonConverter> { new DeviceInfoConverter() }
+            };
+
+            DeviceInfo deviceInfo = JsonConvert.DeserializeObject<DeviceInfo>(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 < zteData.d_sn.Length; 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,'" + zteData.d_sn[i] + "','','BOX','','" + zteData.product_mode + "','" + zteData.product_name + "','" + zteData.material_code + "','" + zteData.batch_no + "','" + zteData.soft_version + "','" + zteData.hd_version + "'," +
-                    "'" + zteData.voltage + "','" + zteData.power + "','" + zteData.order_no + "','" + zteData.big_box_no + "','" + zteData.d_sn[i] + "'," +
-                    "'" + zteData.reserve3[i] + "','" + zteData.DeviceId[i] + "','" + zteData.mac_start[i] + "','" + zteData.mac_end[i] + "','" + zteData.production_date + "',sysdate)", "insert");
+                    "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);
         }
@@ -305,51 +494,69 @@ namespace UAS_MES_NEW.PublicMethod
 
                 // 发送数据
                 byte[] data = Encoding.UTF8.GetBytes(json);
-                byte[] lengthPrefix = BitConverter.GetBytes(data.Length);
-                byte[] packet = new byte[lengthPrefix.Length + data.Length];
+                stream.Write(data, 0, data.Length);
+                Console.WriteLine($"已发送请求: {json}");
+
+                // 接收响应 - 使用安全的方式
+                return ReceiveDataSafely(stream);
+            }
+            catch (Exception ex)
+            {
+                Console.WriteLine($"错误: {ex.Message}");
+                return "";
+            }
+        }
 
-                Buffer.BlockCopy(lengthPrefix, 0, packet, 0, lengthPrefix.Length);
-                Buffer.BlockCopy(data, 0, packet, lengthPrefix.Length, data.Length);
+        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;
 
-                stream.Write(packet, 0, packet.Length);
-                Console.WriteLine($"已发送请求: {json}");
+            try
+            {
+                stream.ReadTimeout = 5000;
 
-                // 接收数据 - 先读取长度
-                byte[] lengthBuffer = new byte[4];
-                int totalBytesRead = 0;
-                while (totalBytesRead < lengthBuffer.Length)
+                while (true)
                 {
-                    int bytesRead = stream.Read(lengthBuffer, totalBytesRead, lengthBuffer.Length - totalBytesRead);
+                    int bytesRead = stream.Read(buffer, 0, buffer.Length);
                     if (bytesRead == 0) break;
+
+                    ms.Write(buffer, 0, bytesRead);
                     totalBytesRead += bytesRead;
-                }
 
-                int messageLength = BitConverter.ToInt32(lengthBuffer, 0);
+                    Console.WriteLine($"本次读取: {bytesRead} 字节, 累计: {totalBytesRead} 字节");
 
-                // 根据长度读取完整数据
-                byte[] messageBuffer = new byte[messageLength];
-                totalBytesRead = 0;
-                while (totalBytesRead < messageLength)
-                {
-                    int bytesRead = stream.Read(messageBuffer, totalBytesRead, messageLength - totalBytesRead);
-                    if (bytesRead == 0) break;
-                    totalBytesRead += bytesRead;
+                    if (totalBytesRead > MAX_SIZE)
+                    {
+                        throw new Exception($"接收数据超过大小限制: {MAX_SIZE} 字节");
+                    }
+
+                    if (!stream.DataAvailable)
+                    {
+                        Thread.Sleep(100);
+                        if (!stream.DataAvailable) break;
+                    }
                 }
 
-                string responseMessage = Encoding.UTF8.GetString(messageBuffer, 0, totalBytesRead);
-                Console.WriteLine($"收到响应: {responseMessage}");
+                byte[] receivedData = ms.ToArray();
 
-                return responseMessage;
-            }
-            catch (SocketException ex)
-            {
-                Console.WriteLine($"网络错误: {ex.Message}");
+                // 直接使用GBK编码(最常用的中文编码)
+                Encoding chineseEncoding = Encoding.GetEncoding("GBK");
+                string response = chineseEncoding.GetString(receivedData);
+
+                Console.WriteLine($"使用GBK编码的响应: {response}");
+                return response;
             }
-            catch (Exception ex)
+            catch (TimeoutException)
             {
-                Console.WriteLine($"错误: {ex.Message}");
+                byte[] partialData = ms.ToArray();
+                Encoding chineseEncoding = Encoding.GetEncoding("GBK");
+                string partialResponse = chineseEncoding.GetString(partialData);
+                Console.WriteLine($"接收超时,已接收数据: {partialResponse}");
+                return partialResponse;
             }
-            return "";
         }
 
         public static readonly uint PROTOCOL_FLAG = 0x4C4F4F54;
@@ -414,7 +621,7 @@ namespace UAS_MES_NEW.PublicMethod
                     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);
@@ -428,7 +635,7 @@ namespace UAS_MES_NEW.PublicMethod
                     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)
+                    if (stHead.getFlag() == FACT_DATA_HEAD.PROTOCOL_FLAG)
                     {
                         int nPos = 0;
                         nSize = stHead.getDatalen();
@@ -444,7 +651,7 @@ namespace UAS_MES_NEW.PublicMethod
                         }
                         strResp = Encoding.Default.GetString(bytRecv, 0, nSize);
                     }
-                    //else nRet = -11;
+                    else nRet = -11;
                 }
                 else nRet = -10;
                 break;