HttpServer.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Dynamic;
  5. using System.IO;
  6. using System.Net;
  7. using System.Net.Sockets;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using Newtonsoft.Json;
  11. using Newtonsoft.Json.Linq;
  12. using UAS_MES_NEW.DataOperate;
  13. using UAS_MES_NEW.Entity;
  14. namespace UAS_MES_NEW.PublicMethod
  15. {
  16. public class BindItem
  17. {
  18. [JsonProperty("bindKey")]
  19. public string BindKey { get; set; }
  20. [JsonProperty("bindValue")]
  21. public string BindValue { get; set; }
  22. [JsonProperty("keyType")]
  23. public string KeyType { get; set; }
  24. [JsonProperty("keyValue")]
  25. public string KeyValue { get; set; }
  26. [JsonProperty("hashType")]
  27. public string HashType { get; set; }
  28. [JsonProperty("hashKey")]
  29. public string HashKey { get; set; }
  30. }
  31. public class RootObject
  32. {
  33. [JsonProperty("productModuleType")]
  34. public string ProductModuleType { get; set; }
  35. [JsonProperty("productMainClass")]
  36. public string ProductMainClass { get; set; }
  37. [JsonProperty("productMediumClass")]
  38. public string ProductMediumClass { get; set; }
  39. [JsonProperty("productSubClass")]
  40. public string ProductSubClass { get; set; }
  41. [JsonProperty("task")]
  42. public string Task { get; set; }
  43. [JsonProperty("processType")]
  44. public string ProcessType { get; set; }
  45. [JsonProperty("userId")]
  46. public string UserId { get; set; }
  47. [JsonProperty("bindList")]
  48. public List<BindItem> BindList { get; set; }
  49. }
  50. public class ZteData
  51. {
  52. public string tool_name { get; set; }
  53. public string response { get; set; }
  54. public int status { get; set; }
  55. public string product_name { get; set; }
  56. public string product_mode { get; set; }
  57. public string material_code { get; set; }
  58. public string batch_no { get; set; }
  59. public string production_date { get; set; }
  60. public string big_box_no { get; set; }
  61. public string box_no { get; set; }
  62. public string reserve10 { get; set; }
  63. public int packing_num { get; set; }
  64. public string soft_version { get; set; }
  65. public string hd_version { get; set; }
  66. public string voltage { get; set; }
  67. public string power { get; set; }
  68. public string order_no { get; set; }
  69. public string[] d_sn { get; set; }
  70. public string[] mac_start { get; set; }
  71. public string[] mac_end { get; set; }
  72. public string[] DeviceId { get; set; }
  73. public string[] dev_en_no { get; set; }
  74. public string[] reserve3 { get; set; }
  75. public string[] reserve4 { get; set; }
  76. }
  77. class HttpServer
  78. {
  79. static DataHelper dh = new DataHelper();
  80. public static int SN_SERVICE_PORT = 8234;
  81. public static int MAX_BUF_SIZE = 4096;
  82. static string ComputeSha256Hash(string input)
  83. {
  84. using (SHA256 sha256 = SHA256.Create())
  85. {
  86. byte[] bytes = Encoding.UTF8.GetBytes(input);
  87. byte[] hashBytes = sha256.ComputeHash(bytes);
  88. StringBuilder builder = new StringBuilder();
  89. for (int i = 0; i < hashBytes.Length; i++)
  90. {
  91. builder.Append(hashBytes[i].ToString("x2"));
  92. }
  93. return builder.ToString().ToUpper();
  94. }
  95. }
  96. //获取SN的EN号,彩盒标机身标一个工站一起打印,需要SN单个获取
  97. public static void GetEN(string iSN)
  98. {
  99. 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");
  100. string prefix = "";
  101. string regcode = "";
  102. string makecode = "";
  103. if (dt.Rows.Count > 0)
  104. {
  105. prefix = dt.Rows[0]["pr_prefix"].ToString();
  106. regcode = dt.Rows[0]["pr_regcode"].ToString();
  107. makecode = dt.Rows[0]["ms_makecode"].ToString();
  108. }
  109. dynamic obj = new ExpandoObject();
  110. obj.tool_name = "zte";
  111. obj.request = "Storage2";
  112. obj.User = "mes";
  113. obj.password = "258456";
  114. obj.po_sn = iSN;
  115. obj.wholeDeviceCode = "";
  116. obj.reg_code = regcode;
  117. obj.prefix_en_no = prefix;
  118. obj.prefix_big_box = "";
  119. obj.packing_num = "";
  120. obj.isn = prefix;
  121. string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
  122. string returnstr = SendData(json);
  123. JObject deviceObj = JObject.Parse(returnstr);
  124. string WholeDeviceCode = deviceObj["WholeDeviceCode"].ToString();
  125. string SN = deviceObj["SN"].ToString();
  126. string dev_en_no = deviceObj["dev_en_no"].ToString();
  127. string mac = deviceObj["mac"].ToString();
  128. string mac_start = deviceObj["mac_start"].ToString();
  129. string mac_end = deviceObj["mac_end"].ToString();
  130. string reg_code = deviceObj["reg_code"].ToString();
  131. string reserve3 = deviceObj["reserve3"].ToString();
  132. string device_type = deviceObj["device_type"].ToString();
  133. string en_no = deviceObj["en_no"].ToString();
  134. 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)" +
  135. "values(ZTEDATA_seq.nextval,'" + SN + "','" + WholeDeviceCode + "','" + dev_en_no + "','" + iSN + "','" + makecode + "','彩盒机身标','','" + mac + "','" + mac_start + "','" + mac_end + "','" + reserve3 + "','" + en_no + "','" + device_type + "','" + reg_code + "')", "insert");
  136. Console.WriteLine(json);
  137. }
  138. //发送外箱号数据,打印前获取
  139. public static void SendBoxData(string iBox)
  140. {
  141. string sn = dh.getFieldDataByCondition("packagedetail", "replace(wm_concat(pd_barcode),',','-')", "pd_outboxcode='" + iBox + "'").ToString();
  142. 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");
  143. string pr_custmachinetype = "";
  144. string makecode = "";
  145. if (dt.Rows.Count > 0)
  146. {
  147. pr_custmachinetype = dt.Rows[0]["pr_custmachinetype"].ToString();
  148. makecode = dt.Rows[0]["ms_makecode"].ToString();
  149. }
  150. var root = new RootObject
  151. {
  152. ProductModuleType = "整机",
  153. ProductMainClass = "固网_CPE",
  154. ProductMediumClass = "CPE",
  155. ProductSubClass = pr_custmachinetype,
  156. Task = makecode,
  157. ProcessType = "生产过程",
  158. UserId = User.UserName,
  159. BindList = new List<BindItem>()
  160. };
  161. root.BindList.Add(new BindItem
  162. {
  163. BindKey = "cartonSn",
  164. BindValue = iBox,
  165. KeyType = "macbox",
  166. KeyValue = sn,
  167. HashType = "SHA256",
  168. HashKey = ComputeSha256Hash(sn)
  169. });
  170. dt = (DataTable)dh.ExecuteSql("select pd_barcode from packagedetail pd_outboxcode='" + iBox + "'", "select");
  171. for (int i = 0; i < dt.Rows.Count; i++)
  172. {
  173. root.BindList.Add(new BindItem
  174. {
  175. BindKey = "mac",
  176. BindValue = dt.Rows[i]["pd_barcode"].ToString(),
  177. KeyType = "EN",
  178. KeyValue = "4Y12R9300001",
  179. HashType = "NON-HASH",
  180. HashKey = "4Y12R9300001"
  181. });
  182. root.BindList.Add(new BindItem
  183. {
  184. BindKey = "mac",
  185. BindValue = dt.Rows[i]["pd_barcode"].ToString(),
  186. KeyType = "电源条码",
  187. KeyValue = "1U1Y2505100013640",
  188. HashType = "NON-HASH",
  189. HashKey = "1U1Y2505100013640"
  190. });
  191. root.BindList.Add(new BindItem
  192. {
  193. BindKey = "mac",
  194. BindValue = dt.Rows[i]["pd_barcode"].ToString(),
  195. KeyType = "JY-License",
  196. KeyValue = "Qk1K4rmuowTDl+NEtSIeHx1td6Tzzm0wDrw/AMCvJ6mrXQ5wsSgoxia+T5Cj+uH4xrGUrjGrZvh/WUQN88iDrPO7kuTA0mvo/Ay+AsFJYnn00JQYQkN9ul+a+Qh0EPBqCVa4ikllHcD1Pqq4Eubs6XXNFhKOtK7F7FMotfGzzAVg7RhKVoVRVFcK6ubSVWXW+SnGx5muH+WZPaiHLjt+kxBR8tZJuBl1LQvMWP74JSWKkcFWwcWlARnCJePvRTvKTDd5e7q9rpBpAc7Z79XYQ6Fs4eXM44O6/hA88YW/BK0TZq3AaaMxH8BpJnwZt4lIyuqXispeaB2eieFBR0JwWg==",
  197. HashType = "SHA256",
  198. HashKey = ComputeSha256Hash(sn),
  199. }); ;
  200. }
  201. string json = JsonConvert.SerializeObject(root, Formatting.Indented);
  202. string returnstr = SendData(json);
  203. Console.WriteLine(json);
  204. }
  205. //获取外箱号信息
  206. public static void GetOutBoxInfo(string iBox)
  207. {
  208. dynamic obj = new ExpandoObject();
  209. var expandoDict = obj as IDictionary<string, object>;
  210. DataTable dt = (DataTable)dh.ExecuteSql("select pd_barcode,pd_makecode from packagedetail where pd_outboxcode='" + iBox + "'", "select");
  211. string makecode = "";
  212. for (int i = 0; i < dt.Rows.Count; i++)
  213. {
  214. string enNoKey = $"en_no{i}";
  215. string enNoValue = dt.Rows[i]["pd_barcode"].ToString();
  216. expandoDict[enNoKey] = enNoValue;
  217. makecode = dt.Rows[i]["pd_makecode"].ToString();
  218. }
  219. obj.request = "Q_wai_xiang";
  220. obj.packing_num = 20;
  221. obj.User = "mes";
  222. obj.po_sn = makecode;
  223. obj.password = "258456";
  224. obj.tool_name = "zte";
  225. obj.noType = 0;
  226. string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
  227. string returnstr = SendData(json);
  228. ZteData zteData = JsonConvert.DeserializeObject<ZteData>(returnstr);
  229. //将返回的信息存入数据库
  230. for (int i = 0; i < zteData.d_sn.Length; i++)
  231. {
  232. 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, " +
  233. "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)" +
  234. "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 + "'," +
  235. "'" + zteData.voltage + "','" + zteData.power + "','" + zteData.order_no + "','" + zteData.big_box_no + "','" + zteData.d_sn[i] + "'," +
  236. "'" + zteData.reserve3[i] + "','" + zteData.DeviceId[i] + "','" + zteData.mac_start[i] + "','" + zteData.mac_end[i] + "','" + zteData.production_date + "',sysdate)", "insert");
  237. }
  238. Console.WriteLine(json);
  239. }
  240. //获取栈板信息
  241. public static void GetPalletInfo(string iBox)
  242. {
  243. DataTable dt = (DataTable)dh.ExecuteSql("select pa_outboxcode,pa_makecode from package where pa_mothercode='" + iBox + "'", "select");
  244. dynamic obj = new ExpandoObject();
  245. var expandoDict = obj as IDictionary<string, object>;
  246. string makecode = "";
  247. for (int i = 0; i < dt.Rows.Count; i++)
  248. {
  249. string enNoKey = $"big_box_no{i}";
  250. string enNoValue = dt.Rows[i]["pa_outboxcode"].ToString();
  251. expandoDict[enNoKey] = enNoValue;
  252. makecode = dt.Rows[i]["pa_makecode"].ToString();
  253. }
  254. obj.request = "pallet";
  255. obj.packing_num = dt.Rows.Count;
  256. obj.User = "mes";
  257. obj.po_sn = makecode;
  258. obj.password = "258456";
  259. obj.tool_name = "zte";
  260. string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
  261. string returnstr = SendData(json);
  262. Console.WriteLine(returnstr);
  263. Console.WriteLine(json);
  264. }
  265. //发送数据
  266. public static string SendData(string json)
  267. {
  268. string serverIP = "10.1.162.175";
  269. int port = 8234;
  270. try
  271. {
  272. TcpClient client = new TcpClient();
  273. client.Connect(serverIP, port);
  274. NetworkStream stream = client.GetStream();
  275. // 发送数据
  276. byte[] data = Encoding.UTF8.GetBytes(json);
  277. byte[] lengthPrefix = BitConverter.GetBytes(data.Length);
  278. byte[] packet = new byte[lengthPrefix.Length + data.Length];
  279. Buffer.BlockCopy(lengthPrefix, 0, packet, 0, lengthPrefix.Length);
  280. Buffer.BlockCopy(data, 0, packet, lengthPrefix.Length, data.Length);
  281. stream.Write(packet, 0, packet.Length);
  282. Console.WriteLine($"已发送请求: {json}");
  283. // 接收数据 - 先读取长度
  284. byte[] lengthBuffer = new byte[4];
  285. int totalBytesRead = 0;
  286. while (totalBytesRead < lengthBuffer.Length)
  287. {
  288. int bytesRead = stream.Read(lengthBuffer, totalBytesRead, lengthBuffer.Length - totalBytesRead);
  289. if (bytesRead == 0) break;
  290. totalBytesRead += bytesRead;
  291. }
  292. int messageLength = BitConverter.ToInt32(lengthBuffer, 0);
  293. // 根据长度读取完整数据
  294. byte[] messageBuffer = new byte[messageLength];
  295. totalBytesRead = 0;
  296. while (totalBytesRead < messageLength)
  297. {
  298. int bytesRead = stream.Read(messageBuffer, totalBytesRead, messageLength - totalBytesRead);
  299. if (bytesRead == 0) break;
  300. totalBytesRead += bytesRead;
  301. }
  302. string responseMessage = Encoding.UTF8.GetString(messageBuffer, 0, totalBytesRead);
  303. Console.WriteLine($"收到响应: {responseMessage}");
  304. return responseMessage;
  305. }
  306. catch (SocketException ex)
  307. {
  308. Console.WriteLine($"网络错误: {ex.Message}");
  309. }
  310. catch (Exception ex)
  311. {
  312. Console.WriteLine($"错误: {ex.Message}");
  313. }
  314. return "";
  315. }
  316. public static readonly uint PROTOCOL_FLAG = 0x4C4F4F54;
  317. public static byte[] BuildPacket(string jsonData)
  318. {
  319. if (string.IsNullOrEmpty(jsonData))
  320. {
  321. throw new ArgumentException("JSON数据不能为空");
  322. }
  323. using (MemoryStream ms = new MemoryStream())
  324. {
  325. // 1. 写入flag (小端序)
  326. byte[] flagBytes = BitConverter.GetBytes(PROTOCOL_FLAG);
  327. ms.Write(flagBytes, 0, 4);
  328. // 2. 将JSON字符串转换为UTF8字节数组
  329. byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonData);
  330. // 3. 写入data_len (小端序)
  331. byte[] lengthBytes = BitConverter.GetBytes(jsonBytes.Length);
  332. ms.Write(lengthBytes, 0, 4);
  333. // 4. 写入data
  334. ms.Write(jsonBytes, 0, jsonBytes.Length);
  335. return ms.ToArray();
  336. }
  337. }
  338. public static string ToServerReq(string strJSON)
  339. {
  340. int nRet = 0;
  341. string strServerIP = "10.1.162.175";
  342. string strResp = "";
  343. IPAddress ip = IPAddress.Parse(strServerIP);
  344. Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  345. while (true)
  346. {
  347. try
  348. {
  349. clientSocket.Connect(new IPEndPoint(ip, SN_SERVICE_PORT));
  350. }
  351. catch
  352. {
  353. nRet = -13;
  354. break;
  355. }
  356. try
  357. {
  358. FACT_DATA_HEAD stHead = new FACT_DATA_HEAD(null);
  359. byte[] bytJson = Encoding.UTF8.GetBytes(strJSON); //Encoding.ASCII.GetBytes(strJSON);
  360. stHead.setDataLen(bytJson.Length);
  361. byte[] bytBuf = new byte[FACT_DATA_HEAD.MY_LEN + bytJson.Length];
  362. byte[] bytSrcHead = stHead.getBytes();
  363. Array.Copy(bytSrcHead, 0, bytBuf, 0, bytSrcHead.Length);
  364. Array.Copy(bytJson, 0, bytBuf, FACT_DATA_HEAD.MY_LEN, bytJson.Length);
  365. clientSocket.Send(bytBuf);
  366. }
  367. catch
  368. {
  369. nRet = -12;
  370. break;
  371. }
  372. byte[] bytRecv = new byte[MAX_BUF_SIZE];
  373. int nRecvSize = 0, nSize = 0;
  374. nRecvSize = clientSocket.Receive(bytRecv, 0, FACT_DATA_HEAD.MY_LEN, SocketFlags.None);
  375. // string strTmp;
  376. // strTmp = string.Format("clientSocket.Receive={0}", nRecvSize);
  377. // Trace.WriteLine(strTmp);
  378. if (nRecvSize > 0)
  379. {
  380. FACT_DATA_HEAD stHead = new FACT_DATA_HEAD(bytRecv);
  381. Console.WriteLine(stHead.getFlag());
  382. Console.WriteLine(FACT_DATA_HEAD.PROTOCOL_FLAG);
  383. //if (stHead.getFlag() == FACT_DATA_HEAD.PROTOCOL_FLAG)
  384. {
  385. int nPos = 0;
  386. nSize = stHead.getDatalen();
  387. while (nPos < nSize)
  388. {
  389. nRecvSize = clientSocket.Receive(bytRecv, nPos, 1869881979 - nPos, SocketFlags.None);
  390. if (nRecvSize < 0)
  391. {
  392. nRet = -14;
  393. break;
  394. }
  395. nPos += nRecvSize;
  396. }
  397. strResp = Encoding.Default.GetString(bytRecv, 0, nSize);
  398. }
  399. //else nRet = -11;
  400. }
  401. else nRet = -10;
  402. break;
  403. }
  404. if (nRet > -13) clientSocket.Shutdown(SocketShutdown.Both);
  405. clientSocket.Close();
  406. return strResp;
  407. }
  408. }
  409. }