1
czw
2025-07-08 9ca7e0307c853871aa984c25eacee18eee01e02d
2025Äê6ÔÂ12ÈÕ/AuxAllWCS/Build/Project/´úÂë/VS×Ô¶¨ÒåÀà/AutoThread.cs
@@ -21,6 +21,12 @@
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;
using GZ.Device.Agv;
namespace GZ.Projects.AuxAllWCS
{
@@ -72,6 +78,8 @@
            }
            // æ‰§è¡Œå§”托
            if (methodName != "TaskEverythingRun")
                return null;
            return methodDelegate.DynamicInvoke(args);
        }
@@ -121,7 +129,7 @@
        public string WriteLine(string value = "")
        {
            // åœ¨è¿™é‡Œæ‹¦æˆªå¤„理输出
@@ -248,9 +256,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
                        {
@@ -283,19 +293,24 @@
                            RedisHelper.Add($"维希尔抓臂1.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("维希尔抓臂1.R10", "true", "维希尔抓臂1Queue");
                                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($"维希尔抓臂1.R44_LAST", "false", out string msg);
                            }
@@ -305,6 +320,10 @@
                            }
                        }
                        else { TcpServer.TcpServerSend(VERX.deviceNo[0], GZ.Device.PLC.PlcHelper.Hex2Bin("544F4E")); }
                    }
                    else if (!tag.wxr1.R10)
                    {
                        TcpServer.TrayIps.Remove(VERX.deviceNo[0]);
                    }
                }
            }
@@ -321,9 +340,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
                        {
@@ -355,19 +376,23 @@
                            RedisHelper.Add($"维希尔抓臂1.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("维希尔抓臂1.R10", "true", "维希尔抓臂1Queue");
                                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($"维希尔抓臂1.R46_LAST", "false", out string msg);
                            }
@@ -377,6 +402,10 @@
                            }
                        }
                        else { TcpServer.TcpServerSend(VERX.deviceNo[1], GZ.Device.PLC.PlcHelper.Hex2Bin("544F4E")); }
                    }
                    else if (!tag.wxr1.R11)
                    {
                        TcpServer.TrayIps.Remove(VERX.deviceNo[1]);
                    }
                }
            }
@@ -393,9 +422,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
                        {
@@ -427,19 +458,23 @@
                            RedisHelper.Add($"维希尔抓臂2.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("维希尔抓臂1.R10", "true", "维希尔抓臂1Queue");
                                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($"维希尔抓臂2.R44_LAST", "false", out string msg);
                            }
@@ -449,6 +484,10 @@
                            }
                        }
                        else { TcpServer.TcpServerSend(VERX.deviceNo[0], GZ.Device.PLC.PlcHelper.Hex2Bin("544F4E")); }
                    }
                    else if (!tag.wxr2.R10)
                    {
                        TcpServer.TrayIps.Remove(VERX.deviceNo[0]);
                    }
                }
            }
@@ -466,9 +505,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
                        {
@@ -492,16 +533,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($"维希尔抓臂2.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
@@ -509,21 +553,38 @@
                                sceneType = 1,
                                cntrCode = traycode,
                            }));
                            if (str.Contains("true"))
                            var strr = JsonConvert.DeserializeObject<Mesrespone>(str);
                            if (strr != null && strr.success)
                            {
                                //Conn.默认Redis.SetValue("维希尔抓臂1.R10", "true", "维希尔抓臂1Queue");
                                tag.wxr2.R11 = true;
                                //Conn.默认Redis.SetValue("维希尔抓臂1.R11", "true", "维希尔抓臂1Queue");
                                //tag.wxr2.R11 = true;
                                LogHelper.Info($"Threadwxr2R。。  -写R11 true");
                                Conn.默认Redis.SetValue(VERX.deviceName + ".R11", "true", VERX.deviceName + "Queue");
                                //tag.wxr2.R46_LAST = false;
                                RedisHelper.Add($"维希尔抓臂2.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 ç»´å¸Œå°”2 å³  è®¾å¤‡æœªæ‰¾åˆ°ã€‚ =================> ");
            }
        }
@@ -587,11 +648,18 @@
                }
                if (tag.RGV.taskend == 125)
                {
                    LogHelper.Info($"RGV æœ‰125命令未执行。");
                    LogHelper.Info($"RGV æœ‰125命令未执行。 ");
                    LogHelper.Info($"RGV125命令未执行 ä»»åŠ¡æ•°æ® workmode:{tag.RGV.workMod}\n taskmod{tag.RGV.taskmod} \n t1No:{tag.RGV.taskno1}\n t1do:{tag.RGV.task1do} \n t2No:{tag.RGV.taskno2}\n t2do:{tag.RGV.task2do}\n taskend:{tag.RGV.taskend} ");
                    if (tag.RGV.workMod == 0 && tag.RGV.taskmod == 0 && tag.RGV.taskno1 == tag.RGV.ReadTask1No && tag.RGV.taskno2 == tag.RGV.ReadTask2No)
                    {
                        LogHelper.Info($"RGV125命令未执行 tag.RGV.workMod == 0 && tag.RGV.taskmod == 0 && tag.RGV.taskno1 == tag.RGV.ReadTask1No && tag.RGV.taskno2 == tag.RGV.ReadTask2No  è‡ªåŠ¨æ¸…é™¤125");
                        Conn.默认Redis.SetValue("RGV.taskend", "0", "RGVQueue", false);
                    }
                    System.Threading.Thread.Sleep(3000);
                    return;
                }
                LogHelper.Info($"任务下发 Rgv ä»»åŠ¡ è¿›å…¥ Rgv信息 W1状态{tag.RGV.w1status} ReadTask1No>{tag.RGV.ReadTask1No} bit1taskOver>{tag.RGV.bit1taskOver} W2状态{tag.RGV.w2status} ReadTask2No>{tag.RGV.ReadTask2No} bit2taskOver>{tag.RGV.bit2taskOver}");
                LogHelper.Info($"任务下发 Rgv ä»»åŠ¡ è¿›å…¥ Rgv信息 W1状态{tag.RGV.w1status} ReadTask1No>{tag.RGV.ReadTask1No} 1工位条码:{tag.RGV.bit1Code} bit1taskOver>{tag.RGV.bit1taskOver} W2状态{tag.RGV.w2status} ReadTask2No>{tag.RGV.ReadTask2No} 2工位条码:{tag.RGV.bit2Code} bit2taskOver>{tag.RGV.bit2taskOver}");
                TaskEntity task1 = null;
                TaskEntity task2 = null;
                var task1Isrun = false;
@@ -653,7 +721,7 @@
                                task1.S_B_STATE = "取货完成";
                            }
                            //tag.RGV.bit1taskOver = 0;
                            LogHelper.Info($"RGV 1工位任务{task1.S_TASK_NO} çŠ¶æ€åˆ‡æ¢ä¸º{task1.S_B_STATE}");
                            LogHelper.Info($"RGV 1工位任务{task1.S_TASK_NO} æ¡ç ï¼š{tag.RGV.bit1Code} çŠ¶æ€åˆ‡æ¢ä¸º{task1.S_B_STATE}");
                            //tag.RGV.bit1taskOver_LAST = 1;
                            RedisHelper.Add($"RGV.bit1taskOver_LAST", "1", out string msg);
                            LogHelper.Info($"RGV 1工位任务写处理");
@@ -695,7 +763,7 @@
                                task2.S_B_STATE = "取货完成";
                            }
                            //tag.RGV.bit2taskOver = 0;
                            LogHelper.Info($"RGV 2工位任务{task2.S_TASK_NO} çŠ¶æ€åˆ‡æ¢ä¸º{task2.S_B_STATE}");
                            LogHelper.Info($"RGV 2工位任务{task2.S_TASK_NO} æ¡ç ï¼š{tag.RGV.bit2Code} çŠ¶æ€åˆ‡æ¢ä¸º{task2.S_B_STATE}");
                            RedisHelper.Add($"RGV.bit2taskOver_LAST", "1", out string msg);
                            LogHelper.Info($"RGV 2工位任务写处理");
                            taskservice.Update(task2);
@@ -833,7 +901,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);
@@ -936,7 +1004,18 @@
            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 => taskCOdes.Contains(x.S_ACTION_CODE) && x.N_CREATEMETHOD == 0).OrderBy(x => x.T_CREATE).ToList();
            var timeMorhours = requires.FindAll(x => DateTime.Now.Subtract(x.T_CREATE).TotalHours > 1);
            if (timeMorhours.Any())
            {
                foreach (var mor in timeMorhours)
                {
                    mor.N_CREATEMETHOD = 2;
                    mor.S_REVIEW_COMMENT = "超时不处理";
                    taskActRepository.Update(mor);
                }
                requires = requires.Except(timeMorhours).ToList();
            }
            foreach (var item in requires)
            {
                LogHelper.Info($"ThreadGrats {item.S_TASK_NO} >{item.S_ACTION_CODE}光栅处理 =================> ");
@@ -944,6 +1023,7 @@
                if (tin == -1)
                {
                    item.N_CREATEMETHOD = -1;
                    item.S_REVIEW_COMMENT = $"信号未知{item.S_ACTION_CODE}不处理";
                    taskActRepository.Update(item);
                    continue;
                }
@@ -951,6 +1031,7 @@
                if (task == null)
                {
                    item.N_CREATEMETHOD = -1;
                    item.S_REVIEW_COMMENT = $"任务丢失不处理";
                    taskActRepository.Update(item);
                    continue;
                }
@@ -991,6 +1072,7 @@
                        LogHelper.Info($"ThreadGrats {item.S_TASK_NO} >{item.S_ACTION_CODE} è®¾å¤‡æ˜¯{dev.deviceName} å¼€å¯å…‰æ …处理完成 =================> ");
                        item.N_CREATEMETHOD = 1;
                        item.S_REVIEW_COMMENT = $"光栅开启完成";
                        taskActRepository.Update(item);
                    }
                    //车要进入交互。
@@ -1048,6 +1130,7 @@
                        taskCode = item.S_TASK_NO
                    });
                    item.N_CREATEMETHOD = 1;
                    item.S_REVIEW_COMMENT = $"车子继续任务OK";
                    taskActRepository.Update(item);
                }
            }
@@ -1111,7 +1194,7 @@
                        var listtep = new List<string>();
                        if (Bssx == "1020")
                        {
                            if (tag.SF下料位.RArrive1003 == 1)
                            if (!string.IsNullOrEmpty(tag.SFT下料口托盘.R1003Barcode) && string.IsNullOrEmpty(tag.SFT下料口托盘.R1011Barcode))
                            {
                                listtep = new List<string> { "1012", "1004" };
                            }
@@ -1122,7 +1205,8 @@
                        }
                        else
                        {
                            if (tag.SF下料位.RArrive1005 == 1)
                            //if (tag.SF下料位.RArrive1005 == 1)
                            if (!string.IsNullOrEmpty(tag.SFT下料口托盘.R1005Barcode) && string.IsNullOrEmpty(tag.SFT下料口托盘.R1013Barcode))
                            {
                                listtep = new List<string> { "1014", "1006" };
                            }
@@ -1553,9 +1637,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);
@@ -1564,23 +1651,90 @@
            foreach (var task in tasks)
            {
                LogHelper.Info($"解释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($"解释MES任务 ->{task.S_TASK_NO} {(sx == null ? "非" : "是")}总装机器人任务");
                if (sx == null)
                {
                    LogHelper.Info($"解释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($"解释MES任务 ->{task.S_TASK_NO} ç›´æŽ¥ç”Ÿæˆå¯¹åº”任务 ç»“果:{res}");
                    if (res)
                    if (string.IsNullOrEmpty(task.S_CNTRS) && !string.IsNullOrEmpty(task.S_INDEX))
                    {
                        LogHelper.Info($"解释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($"解释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($"解释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($"解释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($"解释MES任务 ->{task.S_TASK_NO} ç›´æŽ¥ç”Ÿæˆå¯¹åº”任务 ç»“果:{res}");
                        if (res)
                        {
                            LogHelper.Info($"解释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
@@ -1980,13 +2134,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;
                }
            }
        }
@@ -1999,12 +2162,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;
                                        // å¤åˆ¶åˆ°case ä¸Š
                                        //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("已断开WebSocket连接");
        }
    }
    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
    {