From 31beeb3d23e658e5aa2bbb9f251b006095eef15a Mon Sep 17 00:00:00 2001 From: czw <selecti@yeah.net> Date: 星期一, 07 七月 2025 11:05:04 +0800 Subject: [PATCH] 1 --- 2025年6月12日/AuxAllWCS/Build/Project/代码/VS自定义类/AutoThread.cs | 624 +++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 files changed, 584 insertions(+), 40 deletions(-) diff --git "a/2025\345\271\2646\346\234\21012\346\227\245/AuxAllWCS/Build/Project/\344\273\243\347\240\201/VS\350\207\252\345\256\232\344\271\211\347\261\273/AutoThread.cs" "b/2025\345\271\2646\346\234\21012\346\227\245/AuxAllWCS/Build/Project/\344\273\243\347\240\201/VS\350\207\252\345\256\232\344\271\211\347\261\273/AutoThread.cs" index 75f3343..7f33c68 100644 --- "a/2025\345\271\2646\346\234\21012\346\227\245/AuxAllWCS/Build/Project/\344\273\243\347\240\201/VS\350\207\252\345\256\232\344\271\211\347\261\273/AutoThread.cs" +++ "b/2025\345\271\2646\346\234\21012\346\227\245/AuxAllWCS/Build/Project/\344\273\243\347\240\201/VS\350\207\252\345\256\232\344\271\211\347\261\273/AutoThread.cs" @@ -21,6 +21,11 @@ using static System.Runtime.CompilerServices.RuntimeHelpers; using ServiceStack.Configuration; using ServiceStack; +using Spectre.Console; +using System.Net.WebSockets; +using System.Net; +using System.Threading; +using System.IO; namespace GZ.Projects.AuxAllWCS { @@ -72,6 +77,8 @@ } // 鎵ц濮旀墭 + //if (methodName != "TaskEverythingRun") + // return null; return methodDelegate.DynamicInvoke(args); } @@ -116,6 +123,17 @@ tag.Global.SettingsOver = 1; Console.Clear(); } + } + + public string WriteLine(string value = "") + { + + + + + // 鍦ㄨ繖閲屾嫤鎴鐞嗚緭鍑�+ string intercepted = $"[鎷︽埅鍒扮殑杈撳嚭] {value}"; + return intercepted; } /// <summary> @@ -237,9 +255,11 @@ if (VERX != null) { + if (tag.wxr1.R44) + LogHelper.Info($"{VERX.deviceName} R44>{tag.wxr1.R44} R44LAST>{tag.wxr1.R44_LAST} R10>{tag.wxr1.R10}"); if (tag.wxr1.R44 && !tag.wxr1.R44_LAST && tag.wxr1.R10) { - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/200", JsonConvert.SerializeObject(new { @@ -272,19 +292,24 @@ RedisHelper.Add($"缁村笇灏旀姄鑷�.R10_LAST", "false", out string msg); } else - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { //涓婃姤鏍¢獙銆�+ LogHelper.Info($"{VERX.deviceNo[0]} 涓婃姤鏍¢獙>{traycode}"); + ///var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/202", requestJson); var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/202", JsonConvert.SerializeObject(new { sceneType = 1, cntrCode = traycode, })); - if (str.Contains("true")) + var strr = JsonConvert.DeserializeObject<Mesrespone>(str); + if (strr != null && strr.success) + //if (str.Contains("true")) { //Conn.榛樿Redis.SetValue("缁村笇灏旀姄鑷�.R10", "true", "缁村笇灏旀姄鑷�Queue"); - tag.wxr1.R10 = true; + //tag.wxr1.R10 = true; + Conn.榛樿Redis.SetValue(VERX.deviceName + ".R10", "true", VERX.deviceName + "Queue"); //tag.wxr1.R44_LAST = false; RedisHelper.Add($"缁村笇灏旀姄鑷�.R44_LAST", "false", out string msg); } @@ -294,6 +319,10 @@ } } else { TcpServer.TcpServerSend(VERX.deviceNo[0], GZ.Device.PLC.PlcHelper.Hex2Bin("544F4E")); } + } + else if (!tag.wxr1.R10) + { + TcpServer.TrayIps.Remove(VERX.deviceNo[0]); } } } @@ -310,9 +339,11 @@ if (VERX != null) { + if (tag.wxr1.R46) + LogHelper.Info($"{VERX.deviceName} R44>{tag.wxr1.R46} R44LAST>{tag.wxr1.R46_LAST} R10>{tag.wxr1.R11}"); if (tag.wxr1.R46 && !tag.wxr1.R46_LAST && tag.wxr1.R11) { - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/200", JsonConvert.SerializeObject(new { @@ -344,19 +375,23 @@ RedisHelper.Add($"缁村笇灏旀姄鑷�.R11_LAST", "false", out string msg); } else - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { //涓婃姤鏍¢獙銆�+ LogHelper.Info($"{VERX.deviceNo[1]} 涓婃姤鏍¢獙>{traycode}"); ///var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/202", requestJson); var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/202", JsonConvert.SerializeObject(new { sceneType = 1, cntrCode = traycode, })); - if (str.Contains("true")) + var strr = JsonConvert.DeserializeObject<Mesrespone>(str); + if (strr != null && strr.success) + //if (str.Contains("true")) { //Conn.榛樿Redis.SetValue("缁村笇灏旀姄鑷�.R10", "true", "缁村笇灏旀姄鑷�Queue"); - tag.wxr1.R11 = true; + //tag.wxr1.R11 = true; + Conn.榛樿Redis.SetValue(VERX.deviceName + ".R11", "true", VERX.deviceName + "Queue"); //tag.wxr1.R46_LAST = false; RedisHelper.Add($"缁村笇灏旀姄鑷�.R46_LAST", "false", out string msg); } @@ -366,6 +401,10 @@ } } else { TcpServer.TcpServerSend(VERX.deviceNo[1], GZ.Device.PLC.PlcHelper.Hex2Bin("544F4E")); } + } + else if (!tag.wxr1.R11) + { + TcpServer.TrayIps.Remove(VERX.deviceNo[1]); } } } @@ -382,9 +421,11 @@ if (VERX != null) { + if (tag.wxr2.R44) + LogHelper.Info($"{VERX.deviceName} R44>{tag.wxr2.R44} R44LAST>{tag.wxr2.R44_LAST} R10>{tag.wxr2.R10}"); if (tag.wxr2.R44 && !tag.wxr2.R44_LAST && tag.wxr2.R10) { - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/200", JsonConvert.SerializeObject(new { @@ -416,19 +457,23 @@ RedisHelper.Add($"缁村笇灏旀姄鑷�.R10_LAST", "false", out string msg); } else - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { //涓婃姤鏍¢獙銆�+ LogHelper.Info($"{VERX.deviceNo[0]} 涓婃姤鏍¢獙>{traycode}"); ///var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/202", requestJson); var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/202", JsonConvert.SerializeObject(new { sceneType = 1, cntrCode = traycode, })); - if (str.Contains("true")) + var strr = JsonConvert.DeserializeObject<Mesrespone>(str); + if (strr != null && strr.success) + //if (str.Contains("true")) { //Conn.榛樿Redis.SetValue("缁村笇灏旀姄鑷�.R10", "true", "缁村笇灏旀姄鑷�Queue"); - tag.wxr2.R10 = true; + //tag.wxr2.R10 = true; + Conn.榛樿Redis.SetValue(VERX.deviceName + ".R10", "true", VERX.deviceName + "Queue"); //tag.wxr2.R44_LAST = false; RedisHelper.Add($"缁村笇灏旀姄鑷�.R44_LAST", "false", out string msg); } @@ -438,6 +483,10 @@ } } else { TcpServer.TcpServerSend(VERX.deviceNo[0], GZ.Device.PLC.PlcHelper.Hex2Bin("544F4E")); } + } + else if (!tag.wxr2.R10) + { + TcpServer.TrayIps.Remove(VERX.deviceNo[0]); } } } @@ -455,9 +504,11 @@ if (VERX != null) { + if (tag.wxr2.R46) + LogHelper.Info($"{VERX.deviceName} R44>{tag.wxr2.R46} R44LAST>{tag.wxr2.R46_LAST} R10>{tag.wxr2.R11}"); if (tag.wxr2.R46 && !tag.wxr2.R46_LAST && tag.wxr2.R11) { - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/200", JsonConvert.SerializeObject(new { @@ -481,16 +532,19 @@ } else { + //LogHelper.Info($"Threadwxr2R 鎵樼洏鏀剧疆淇″彿1銆傘� -{tag.wxr2.R11_LAST}"); if (tag.wxr2.R11_LAST) //鎵樼洏鏀剧疆淇″彿銆傘� { + //LogHelper.Info($"Threadwxr2R 鎵樼洏鏀剧疆淇″彿1銆傘� -{tag.wxr2.R11}"); if (tag.wxr2.R11) { //tag.wxr2.R11_LAST = false; RedisHelper.Add($"缁村笇灏旀姄鑷�.R11_LAST", "false", out string msg); } else - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { + LogHelper.Info($"{VERX.deviceNo[1]} 涓婃姤鏍¢獙>{traycode}"); //涓婃姤鏍¢獙銆� ///var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/202", requestJson); var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/202", JsonConvert.SerializeObject(new @@ -498,21 +552,38 @@ sceneType = 1, cntrCode = traycode, })); - if (str.Contains("true")) + var strr = JsonConvert.DeserializeObject<Mesrespone>(str); + if (strr != null && strr.success) { - //Conn.榛樿Redis.SetValue("缁村笇灏旀姄鑷�.R10", "true", "缁村笇灏旀姄鑷�Queue"); - tag.wxr2.R11 = true; + //Conn.榛樿Redis.SetValue("缁村笇灏旀姄鑷�.R11", "true", "缁村笇灏旀姄鑷�Queue"); + //tag.wxr2.R11 = true; + + LogHelper.Info($"Threadwxr2R銆傘� -鍐橰11 true"); + Conn.榛樿Redis.SetValue(VERX.deviceName + ".R11", "true", VERX.deviceName + "Queue"); //tag.wxr2.R46_LAST = false; RedisHelper.Add($"缁村笇灏旀姄鑷�.R46_LAST", "false", out string msg); + LogHelper.Info($"Threadwxr2R銆傘� 鏍¢獙涓嬫枡瀹屾垚銆�); } else { //鎶ヨ銆� } } - else { TcpServer.TcpServerSend(VERX.deviceNo[1], GZ.Device.PLC.PlcHelper.Hex2Bin("544F4E")); } + else + { + LogHelper.Info($"Threadwxr2R銆傘� -鍙戦�鎵爜"); + TcpServer.TcpServerSend(VERX.deviceNo[1], GZ.Device.PLC.PlcHelper.Hex2Bin("544F4E")); + } + } + else if (!tag.wxr2.R11) + { + TcpServer.TrayIps.Remove(VERX.deviceNo[1]); } } + } + else + { + Console.WriteLine($"Threadwxr2R 缁村笇灏� 鍙� 璁惧鏈壘鍒般� =================> "); } } @@ -822,7 +893,7 @@ if (tag.RGV.bit1taskOver == 1) tag.RGV.bit1taskOver = 0; - LogHelper.Info($"{task1.S_TASK_NO}> taskend 鍐�0"); + LogHelper.Info($"{task1.S_TASK_NO}> taskend 鍐�125"); Conn.榛樿Redis.SetValue("RGV.taskend", "125", "RGVQueue", false); LogHelper.Info($"{task1.S_TASK_NO}> bit1taskOver_LAST 鍐�0"); RedisHelper.Add($"RGV.bit1taskOver_LAST", "0", out string msg); @@ -925,7 +996,7 @@ var taskCOdes = new List<string> { "Sarrive", "Srelease", "Earrive", "Erelease" }; TaskActRepository taskActRepository = new TaskActRepository(); TaskRepository taskRepository = new TaskRepository(); - var requires = taskActRepository.FindList(x => taskCOdes.Contains(x.S_ACTION_CODE) && x.N_CREATEMETHOD == 0).OrderBy(x => x.T_CREATE); + var requires = taskActRepository.FindList(x => DateTime.Now.Subtract(x.T_CREATE).TotalHours < 1 && taskCOdes.Contains(x.S_ACTION_CODE) && x.N_CREATEMETHOD == 0).OrderBy(x => x.T_CREATE); foreach (var item in requires) { LogHelper.Info($"ThreadGrats {item.S_TASK_NO} >{item.S_ACTION_CODE}鍏夋爡澶勭悊 =================> "); @@ -1542,9 +1613,12 @@ Console.WriteLine($"SA2030 浠诲姟鐘舵�锛� =====>"); Console.WriteLine($"SA2030 浠诲姟鐘舵�锛歿tag.SA2030.RtaskState}- 绌洪棽{tag.SA2030.R5绌洪棽} - barcode:{tag.SA2030.R鎵樼洏鐮亇"); + + + } - public void ResolveMesTask() + public void ResolveMesTask(Tag tag) { TaskRepository taskservice = new TaskRepository(); var tasks = taskservice.FindList(x => (x.S_B_STATE == "MES" || x.S_B_STATE == "People") && x.N_PRIORITY == -88); @@ -1553,23 +1627,90 @@ foreach (var task in tasks) { LogHelper.Info($"瑙i噴MES浠诲姟 ->{task.S_TASK_NO} "); + if (task.S_TYPE?.Trim() == "100") + { + LogHelper.Info($"MES浠诲姟 S_TYPE 100->{task.S_TYPE} "); + } var sx = VERXs?.Find(x => x.location.Contains(task.S_END_LOC)); LogHelper.Info($"瑙i噴MES浠诲姟 ->{task.S_TASK_NO} {(sx == null ? "闈� : "鏄�)}鎬昏鏈哄櫒浜轰换鍔�); if (sx == null) { - LogHelper.Info($"瑙i噴MES浠诲姟 ->{task.S_TASK_NO} 鐩存帴鐢熸垚瀵瑰簲浠诲姟"); - //鐩存帴鐢熸垚瀵瑰簲浠诲姟銆�- var res = TaskProcess.CreateTask(task.S_TASK_NO, task.S_START_LOC, task.S_END_LOC, task.S_TYPE, 6, task.S_CNTRS?.Split(',').ToList() ?? new List<string>()); - - LogHelper.Info($"瑙i噴MES浠诲姟 ->{task.S_TASK_NO} 鐩存帴鐢熸垚瀵瑰簲浠诲姟 缁撴灉锛歿res}"); - if (res) + if (string.IsNullOrEmpty(task.S_CNTRS) && !string.IsNullOrEmpty(task.S_INDEX)) { - LogHelper.Info($"瑙i噴MES浠诲姟 ->{task.S_TASK_NO} 淇敼鏍囪瘑"); - //task.N_PRIORITY = 0; - taskservice.dbcontext.Set<TaskEntity>().Attach(task); - taskservice.dbcontext.Entry(task).Property(x => x.N_PRIORITY).CurrentValue = 0; - taskservice.dbcontext.Entry(task).Property(x => x.N_PRIORITY).IsModified = true; - taskservice.dbcontext.SaveChanges(); + // 鍙枡浠诲姟銆�鎸囧畾鐗╂枡涓嶆寚瀹氭墭鐩橈紝闇�鍑哄簱 + switch (task.S_START_LOC) + { + case "2030": + if (!string.IsNullOrEmpty(tag.SA2030.R鎵樼洏鐮�) + { + var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/224", JsonConvert.SerializeObject(new + { + cntrCode = tag.SA2030.R鎵樼洏鐮� + type = 1 + })); + var strr = JsonConvert.DeserializeObject<MES2234>(str); + if (strr.success && strr.data.materialCode == task.S_INDEX) + { + task.S_CNTRS = tag.SA2030.R鎵樼洏鐮� + taskservice.Update(task); + } + else + { + LogHelper.Info($"瑙i噴MES浠诲姟 ->{task.S_TASK_NO} 2030 鍑哄彛鐨勬墭鐩樼墿鏂欎笉绗﹀悎"); + } + } + else + { + //TODO------------------2027 2220 2013.. 璇嗗埆涓�笅锛屽紑濮嬪簱 + } + break; + case "1019": + if (!string.IsNullOrEmpty(tag.SA1019.R鎵樼洏鐮�) + { + var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/224", JsonConvert.SerializeObject(new + { + cntrCode = tag.SA1019.R鎵樼洏鐮� + type = 2 + })); + var strr = JsonConvert.DeserializeObject<MES2234>(str); + if (strr.success && strr.data.materialCode == task.S_INDEX) + { + task.S_CNTRS = tag.SA2030.R鎵樼洏鐮� + taskservice.Update(task); + } + else + { + LogHelper.Info($"瑙i噴MES浠诲姟 ->{task.S_TASK_NO} 1019 鍑哄彛鐨勬墭鐩樼墿鏂欎笉绗﹀悎"); + } + } + break; + } + } + else + { + if (new List<string> { "2001", "1022", "1025", "3001", "3006" }.Contains(task.S_END_LOC)) + { + //------------------ + } + else if (new List<string> { "1019"/*, "1030"*/, "2030", "3005", "3010" }.Contains(task.S_START_LOC)) //1030 鏄富鍔ㄧ敵璇凤紝 涓嶇敤鍒ゆ柇銆�+ { + + } + + LogHelper.Info($"瑙i噴MES浠诲姟 ->{task.S_TASK_NO} 鐩存帴鐢熸垚瀵瑰簲浠诲姟"); + //鐩存帴鐢熸垚瀵瑰簲浠诲姟銆�+ var res = TaskProcess.CreateTask(task.S_TASK_NO, task.S_START_LOC, task.S_END_LOC, task.S_TYPE, 6, task.S_CNTRS?.Split(',').ToList() ?? new List<string>()); + + LogHelper.Info($"瑙i噴MES浠诲姟 ->{task.S_TASK_NO} 鐩存帴鐢熸垚瀵瑰簲浠诲姟 缁撴灉锛歿res}"); + if (res) + { + LogHelper.Info($"瑙i噴MES浠诲姟 ->{task.S_TASK_NO} 淇敼鏍囪瘑"); + //task.N_PRIORITY = 0; + taskservice.dbcontext.Set<TaskEntity>().Attach(task); + taskservice.dbcontext.Entry(task).Property(x => x.N_PRIORITY).CurrentValue = 0; + taskservice.dbcontext.Entry(task).Property(x => x.N_PRIORITY).IsModified = true; + taskservice.dbcontext.SaveChanges(); + } } } else @@ -1969,13 +2110,22 @@ return new HkReturnResult { reqCode = model.reqCode, code = 0 }; } - - - - - - - + public void TaskEverythingRun() + { + var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); + foreach (var ip in host.AddressList) + { + if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) + { + Console.WriteLine($"ip= {ip.ToString()}"); + new HttpServer(ip.ToString()).HttpServerRun(); + new TcpServer(ip.ToString()); + var server = new EnhancedWebSocketServer($"http://{ip.ToString()}:8809/").StartAsync(); + //var client = new WebSocketClient($"http://{ip.ToString()}:8809/").ConnectAsync(); + break; + } + } + } @@ -1988,12 +2138,406 @@ } + + public class HttpServer + { + System.Net.HttpListener HttpSvcHost = null; + + public static string _listenerPrefix = ""; + public HttpServer(string ip) + { + _listenerPrefix = $"http://{ip}:8808/"; + } + public void HttpServerRun() + { + HttpSvcHost = new System.Net.HttpListener(); + HttpSvcHost.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous; + HttpSvcHost.Prefixes.Add(_listenerPrefix); + HttpSvcHost.Start(); + HttpSvcHost.BeginGetContext(HttpSvcListenerCallback, null); + } + + + private async void HttpSvcListenerCallback(IAsyncResult ar) + { + System.Net.HttpListenerContext context = null; + var data = DateTime.Now; + string apth = ""; + try + { + HttpSvcHost.BeginGetContext(HttpSvcListenerCallback, null); + context = HttpSvcHost.EndGetContext(ar); + System.Net.HttpListenerRequest request = context.Request; + System.Net.HttpListenerResponse response = context.Response; + + using (var reader = new System.IO.StreamReader(request.InputStream, System.Text.Encoding.UTF8)) + { + string requestJson = reader.ReadToEnd(); + System.Net.HttpStatusCode statusCode = 0; + apth = request.Url.AbsolutePath; + string respstr = HttpSvcListenerCallback_he(request.HttpMethod, request.Url.AbsolutePath, requestJson, out statusCode); + string logContent = ""; + logContent += $"\r\n[{request.HttpMethod}]{request.Url.AbsolutePath}"; + logContent += $"\r\n[request]{requestJson}"; + logContent += $"\r\n[response]{respstr}"; + _ = Task.Run(() => + { + Conn.榛樿鏃ュ織?.Info(logContent); + }); + byte[] bytstr = Encoding.UTF8.GetBytes(respstr); + response.StatusCode = (int)statusCode; + response.SendChunked = false; + response.ContentLength64 = bytstr.Length; + //response.OutputStream.Write(bytstr, 0, bytstr.Length); + if (request.Url.AbsolutePath.ToLower().Contains(".js")) + response.ContentType = "application/javascript"; + else if (request.Url.AbsolutePath.ToLower().Contains(".svg")) + response.ContentType = "image/svg+xml"; + // 寮傛鍐欏叆鍝嶅簲 + await response.OutputStream.WriteAsync(bytstr, 0, bytstr.Length); + } + } + catch (Exception ex) + { + _ = Task.Run(() => + { + Conn.榛樿鏃ュ織.Error(ex.ToString()); + }); + } + finally + { + context?.Response.Close(); + Console.WriteLine(apth + "<<>>" + DateTime.Now.Subtract(data).TotalMilliseconds); + } + } + private System.String HttpSvcListenerCallback_he(System.String method, System.String path, System.String requestJson, out System.Net.HttpStatusCode statusCode) + { + try + { + switch (method) + { + case "POST": + { + switch (path) + { + case "/agv/agvCallbackService/agvCallback": + { + statusCode = System.Net.HttpStatusCode.OK; + + LogHelper.Info("ExecuteState Request-haikang锛� + requestJson); + var model = JsonConvert.DeserializeObject<HaiKangOrderInfo>(requestJson); + AutoThread.Instance.OperateHKTaskStatus(model); + return JsonConvert.SerializeObject(new HkReturnResult { reqCode = model.reqCode }); + } + case "/api/Wcs/CreateTask": + { + statusCode = System.Net.HttpStatusCode.OK; + + LogHelper.Info("/api/Wcs/CreateTask锛� + requestJson); + var model = JsonConvert.DeserializeObject<ToWMSMES.CreateTask>(requestJson); + var res = ToWMSMES.CreateTask.CreatemesTask(model); + return JsonConvert.SerializeObject(res); + } + case "/api/Wcs/TestRequestTask": + { + statusCode = System.Net.HttpStatusCode.OK; + LogHelper.Info("/api/Wcs/TestRequestTask锛� + requestJson); + var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/200", requestJson); + return str; + } + case "/api/Wcs/updateStatus": + { + statusCode = System.Net.HttpStatusCode.OK; + LogHelper.Info("/api/Wcs/updateStatus锛� + requestJson); + var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/201", requestJson); + return str; + } + case "/api/Wcs/toMes": + { + statusCode = System.Net.HttpStatusCode.OK; + + LogHelper.Info("/api/Wcs/toMes锛� + requestJson); + var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/202", requestJson); + return str; + } + case "/api/Wcs/CreatePointTask": + { + statusCode = System.Net.HttpStatusCode.OK; + + LogHelper.Info("/api/Wcs/CreatepointTask锛� + requestJson); + var model = JsonConvert.DeserializeObject<ToWMSMES.CreateTask>(requestJson); + var res = ToWMSMES.CreateTask.CreatePointTask(model); + return JsonConvert.SerializeObject(res); + } + } + break; + } + case "GET": + { + switch (path) + { + case var _ when System.Text.RegularExpressions.Regex.IsMatch(path, @"\.(html|ico|js|css)(\?.*)?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase): + { + statusCode = System.Net.HttpStatusCode.OK; + // 澶嶅埗鍒癱ase 涓�+ //var _ when System.Text.RegularExpressions.Regex.IsMatch(path, @"\.(html|ico|js|css)(\?.*)?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase) + var filePath = /*Directory.GetCurrentDirectory() + "\\Static" + "\\" + path.Substring(1);*/System.IO.Path.Combine(Directory.GetCurrentDirectory() + "\\Static", path.Substring(1)); + return File.ReadAllText(filePath); + } + } + break; + } + } + statusCode = System.Net.HttpStatusCode.NotFound; + return ""; + } + catch (Exception ex) + { + Conn.榛樿鏃ュ織.Error(ex.ToString()); + statusCode = System.Net.HttpStatusCode.InternalServerError; + return ""; + } + } + } + + class EnhancedWebSocketServer + { + private HttpListener _listener; + private readonly string _listenerPrefix; + private readonly ConcurrentDictionary<Guid, WebSocket> _connections = new ConcurrentDictionary<Guid, WebSocket>(); + private CancellationTokenSource _cts = new CancellationTokenSource(); + + public EnhancedWebSocketServer(string url) + { + _listenerPrefix = url; + } + + public async Task StartAsync() + { + try + { + _listener = new HttpListener(); + _listener.Prefixes.Add(_listenerPrefix); + _listener.Start(); + Console.WriteLine($"WebSocket鏈嶅姟鍣ㄥ凡鍚姩锛岀洃鍚�{_listenerPrefix}"); + while (!_cts.IsCancellationRequested) + { + HttpListenerContext context = await _listener.GetContextAsync(); + if (context.Request.IsWebSocketRequest) + { + var wsContext = await context.AcceptWebSocketAsync(null); + var connectionId = Guid.NewGuid(); + _connections[connectionId] = wsContext.WebSocket; + _ = HandleConnectionAsync(connectionId, wsContext.WebSocket, _cts.Token); + } + else + { + context.Response.StatusCode = 400; + context.Response.Close(); + } + } + } + catch (Exception ex) when (ex is HttpListenerException || ex is ObjectDisposedException) + { + // 鏈嶅姟鍣ㄥ仠姝㈡椂鐨勬甯稿紓甯�+ Console.WriteLine("鏈嶅姟鍣ㄦ鍦ㄥ仠姝�.."); + } + } + + private async Task HandleConnectionAsync(Guid connectionId, WebSocket webSocket, CancellationToken ct) + { + var buffer = new byte[1024 * 4]; + try + { + while (webSocket.State == WebSocketState.Open && !ct.IsCancellationRequested) + { + var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), ct); + + if (result.MessageType == WebSocketMessageType.Close) + { + await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "瀹㈡埛绔叧闂繛鎺�, ct); + break; + } + + string message = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count); + Console.WriteLine($"杩炴帴 {connectionId} 鏀跺埌娑堟伅: {message}"); + + // 骞挎挱娑堟伅缁欐墍鏈夊鎴风 + await BroadcastMessageAsync($"瀹㈡埛绔�{connectionId} 璇� {message}"); + } + } + catch (WebSocketException ex) + { + Console.WriteLine($"杩炴帴 {connectionId} 閿欒: {ex.WebSocketErrorCode} - {ex.Message}"); + } + catch (Exception ex) + { + Console.WriteLine($"澶勭悊杩炴帴 {connectionId} 鏃跺嚭閿� {ex.Message}"); + } + finally + { + _connections.TryRemove(connectionId, out _); + webSocket?.Dispose(); + Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss.fff")} 杩炴帴 {connectionId} 宸插叧闂�); + } + } + + public async Task BroadcastMessageAsync(string message) + { + var buffer = System.Text.Encoding.UTF8.GetBytes(message); + foreach (var connection in _connections) + { + if (connection.Value.State == WebSocketState.Open) + { + try + { + await connection.Value.SendAsync( + new ArraySegment<byte>(buffer), + WebSocketMessageType.Text, + true, + CancellationToken.None); + } + catch (Exception ex) + { + Console.WriteLine($"骞挎挱娑堟伅鍒拌繛鎺�{connection.Key} 澶辫触: {ex.Message}"); + } + } + } + } + + public async Task StopAsync() + { + _cts.Cancel(); + + // 鍏抽棴鎵�湁杩炴帴 + foreach (var connection in _connections) + { + try + { + if (connection.Value.State == WebSocketState.Open) + { + await connection.Value.CloseAsync( + WebSocketCloseStatus.NormalClosure, + "鏈嶅姟鍣ㄥ叧闂�, + CancellationToken.None); + } + connection.Value.Dispose(); + } + catch (Exception ex) + { + Console.WriteLine($"鍏抽棴杩炴帴 {connection.Key} 鏃跺嚭閿� {ex.Message}"); + } + } + + _listener?.Stop(); + _listener?.Close(); + Console.WriteLine("WebSocket鏈嶅姟鍣ㄥ凡鍋滄"); + } + + } + + internal class WebSocketClient + { + private ClientWebSocket _webSocket = new ClientWebSocket(); + private readonly Uri _serverUri; + + public WebSocketClient(string serverUrl) + { + _serverUri = new Uri(serverUrl); + } + + public async Task ConnectAsync() + { + try + { + await _webSocket.ConnectAsync(_serverUri, CancellationToken.None); + Console.WriteLine("宸茶繛鎺ュ埌WebSocket鏈嶅姟鍣�); + + // 鍚姩鎺ユ敹娑堟伅浠诲姟 + _ = ReceiveMessagesAsync(); + + // 鍙戦�娴嬭瘯娑堟伅 + await SendMessageAsync("Hello, Server!"); + } + catch (Exception ex) + { + Console.WriteLine($"杩炴帴澶辫触: {ex.Message}"); + } + } + + private async Task ReceiveMessagesAsync() + { + var buffer = new byte[1024]; + try + { + while (_webSocket.State == WebSocketState.Open) + { + var result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); + if (result.MessageType == WebSocketMessageType.Close) + { + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); + Console.WriteLine("鏈嶅姟鍣ㄥ叧闂簡杩炴帴"); + break; + } + + string message = Encoding.UTF8.GetString(buffer, 0, result.Count); + Console.WriteLine($"鏀跺埌鏈嶅姟鍣ㄦ秷鎭� {message}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"鎺ユ敹娑堟伅鏃跺嚭閿� {ex.Message}"); + } + } + + public async Task SendMessageAsync(string message) + { + if (_webSocket.State != WebSocketState.Open) + { + Console.WriteLine("WebSocket鏈繛鎺ワ紝鏃犳硶鍙戦�娑堟伅"); + return; + } + + byte[] buffer = Encoding.UTF8.GetBytes(message); + await _webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None); + } + + public async Task DisconnectAsync() + { + if (_webSocket.State == WebSocketState.Open) + { + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "瀹㈡埛绔叧闂繛鎺�, CancellationToken.None); + } + _webSocket.Dispose(); + Console.WriteLine("宸叉柇寮�ebSocket杩炴帴"); + } + } + + class Messss { public bool success { get; set; } public Ddata data { get; set; } public object extra { get; set; } } + class Mesrespone + { + public bool success { get; set; } + public string msg { get; set; } + public object extra { get; set; } + } + + class MES2234 + { + public bool success { get; set; } + public ML data { get; set; } + } + + public class ML + { + public string materialCode { get; set; } + public int lineNum { get; set; } + } public class Ddata { -- Gitblit v1.9.1