From 73a077d76b715aee6b9f384b087a6792a84989d8 Mon Sep 17 00:00:00 2001
From: huangxiaoqiang <1247017146@qq.com>
Date: 星期二, 03 六月 2025 11:35:52 +0800
Subject: [PATCH] 代码提交

---
 项目代码/WMS/WIDESEA_WMSServer/WIDESEA_StorageSocketServices/SocketClientService.cs | 1238 +++++++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 879 insertions(+), 359 deletions(-)

diff --git "a/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_StorageSocketServices/SocketClientService.cs" "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_StorageSocketServices/SocketClientService.cs"
index 0b968d9..0319ba1 100644
--- "a/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_StorageSocketServices/SocketClientService.cs"
+++ "b/\351\241\271\347\233\256\344\273\243\347\240\201/WMS/WIDESEA_WMSServer/WIDESEA_StorageSocketServices/SocketClientService.cs"
@@ -29,6 +29,9 @@
 using Microsoft.Extensions.DependencyInjection;
 using WIDESEA_IBusinessesRepository;
 using WIDESEA_Repository;
+using static MailKit.Telemetry;
+using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
+using System.Runtime.InteropServices;
 
 namespace WIDESEA_StorageSocketServices
 {
@@ -39,40 +42,30 @@
         const byte ETX = 3;
         private readonly ILogger<SocketClientService> _logger;
         private readonly LogFactory LogFactory = new LogFactory();
-        //private readonly IDt_TaskService _taskService;
         private readonly IDt_StationManagerRepository _stationManagerRepository;
         private readonly IDt_TaskRepository BaseDal;
         Connection connection = AppSettings.Configuration.GetSection("Connection").Get<Connection>();
         string url = AppSettings.Configuration["AGVIP"];
-        private readonly IUnitOfWorkManage _unitOfWorkManage;
-        private readonly IStockInfoRepository _stockInfoRepository;
-        private readonly IDt_Task_HtyRepository _task_HtyRepository;
-        private readonly IMapper _mapper;
-        private readonly ILocationInfoRepository _locationRepository;
         private readonly IDt_TaskService _taskService;
         private readonly IDt_HostLogRepository _hostLogRepository;
         private bool _IsOnline=false;
+        public DateTime Time { get; set; } = DateTime.Now;
 
 
-        public SocketClientService(IDt_TaskService TaskService, IDt_TaskRepository TaskRepository, IDt_StationManagerRepository stationManagerRepository, ILogger<SocketClientService> logger, ILocationInfoRepository locationInfoRepository,IDt_HostLogRepository hostLogRepository)
+        public SocketClientService(IDt_TaskService TaskService, IDt_TaskRepository TaskRepository, IDt_StationManagerRepository stationManagerRepository, ILogger<SocketClientService> logger,IDt_HostLogRepository hostLogRepository)
         {
             BaseDal = TaskRepository;
             _stationManagerRepository = stationManagerRepository;
             _logger = logger;
             _taskService = TaskService;
-            _locationRepository = locationInfoRepository;
             _hostLogRepository = hostLogRepository;
-            #region
-            //if (App.RootServices != null)
-            //{
-            //    IDt_TaskRepository? BaseDal = App.RootServices.CreateScope().ServiceProvider.GetService(typeof(IDt_TaskRepository)) as IDt_TaskRepository;
-            //    IDt_TaskService? _taskService = App.RootServices.CreateScope().ServiceProvider.GetService(typeof(IDt_TaskService)) as IDt_TaskService;
-            //    ILocationInfoRepository? _locationRepository = App.RootServices.CreateScope().ServiceProvider.GetService(typeof(ILocationInfoRepository)) as ILocationInfoRepository;
-            //    IDt_StationManagerRepository? _stationManagerRepository = App.RootServices.CreateScope().ServiceProvider.GetService(typeof(IDt_StationManagerRepository)) as IDt_StationManagerRepository;
-            //}
-            #endregion
         }
 
+        /// <summary>
+        /// TCPSocket杩炴帴
+        /// </summary>
+        /// <param name="IP"></param>
+        /// <param name="Port"></param>
         public void ConnectServer(string IP, int Port)
         {
             try
@@ -85,7 +78,7 @@
                 }
 
                 //鍒涘缓璐熻矗閫氫俊鐨剆ocket
-                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+                socket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                 IPAddress ip = IPAddress.Parse(IP);
                 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(Port));
 
@@ -94,9 +87,14 @@
 
                 _logger.LogInformation("Socket杩炴帴鎴愬姛");
                 ConsoleHelper.WriteSuccessLine("Socket杩炴帴鎴愬姛");
+
+                DeleteHostLog(910);
+
                 _IsOnline = true;
                 RequestCommunication();
-                DeviceStateReport("I");
+                AGVStatusRespone status = GetAGVStatus();
+
+                DeviceStateReport(GetAGVStatus(status.RuntimeStatus));
 
                 //寮�鍚竴涓柊鐨勭嚎绋嬩笉鍋滅殑鎺ユ敹鏈嶅姟绔彂鏉ョ殑淇℃伅
                 Thread th = new Thread(Receive);
@@ -111,12 +109,19 @@
                 HandleDisconnection();
             }
         }
+
+
         public bool Socketonline()
         {
             return _IsOnline;
         }
+
+        /// <summary>
+        /// 绾跨▼璇诲彇鏁版嵁
+        /// </summary>
         void Receive()
         {
+            Time = DateTime.Now;
             while (true)
             {
                 try
@@ -147,6 +152,7 @@
                         var str = Encoding.UTF8.GetString(newArray);
                         string receivedChecksum = str.Substring(str.Length - 2);
 
+                        LogFactory.GetLog("鎺ユ敹Socket鏁版嵁").Info(true, $"{JsonConvert.SerializeObject(GetParse(str))}{Environment.NewLine}");
                         if (calculatedChecksum == receivedChecksum)
                         {
                             var x = Encoding.UTF8.GetString(newArray);
@@ -162,23 +168,29 @@
                         }
                         else
                         {
-                            LogFactory.GetLog("Socket鎺ユ敹鏁版嵁").Error(true, "鏍¢獙澶辫触");
+                            CheckSum("3");
+                            LogFactory.GetLog("Socket鎺ユ敹鏁版嵁").Error(true, $"CheckSum鏍¢獙澶辫触,瑙f瀽{calculatedChecksum}銆佽鍙杮receivedChecksum}");
                         }
                     }
                     else
                     {
-                        LogFactory.GetLog("Socket鎺ユ敹鏁版嵁").Error(true, $"鏃犳晥鎶ユ枃鏍煎紡:{JsonConvert.SerializeObject(Y)}");
+                        LogFactory.GetLog("Socket鎺ユ敹鏁版嵁").Error(true, $"鏃犳晥鎶ユ枃鏍煎紡:{JsonConvert.SerializeObject(Y)}{Environment.NewLine}");
                     }
                 }
                 catch
                 {
                     _IsOnline = false;
                     HandleDisconnection();
-
                 }
             }
         }
 
+
+        /// <summary>
+        /// 浣滀笟JobType
+        /// </summary>
+        /// <param name="cmdId"></param>
+        /// <param name="x"></param>
         private void ProcessCommand(string cmdId, string x)
         {
             switch (cmdId)
@@ -207,17 +219,58 @@
                 case "909":
                     DeviceStatusReportRequest();
                     break;
+                case "987":
+                    FireAlarm(x.Substring(21, 6), x.Substring(15, 5));
+                    break;
+                case "301":
+                    UpdateLocalTime(x.Substring(30), x.Substring(15, 5));
+                    break;
+                case "918":
+                    break;
                 default:
+                    CheckSum("1");
                     break;
             }
         }
 
-        private void HandleDisconnection()
+        #region
+        //private void HandleDisconnection()
+        //{
+        //    int attempts = 100;
+        //    do
+        //    {
+        //        string message = "杩炴帴宸叉柇寮�..." + '\n';
+        //        message += "绛夊緟5绉掑悗閲嶆柊杩炴帴" + '\n';
+        //        Console.WriteLine(message);
+
+        //        // 鍏抽棴褰撳墠杩炴帴
+        //        try
+        //        {
+        //            socket?.Close();
+        //        }
+        //        catch { }
+
+        //        // 绛夊緟5绉�
+        //        Thread.Sleep(5000);
+
+        //        // 灏濊瘯閲嶆柊杩炴帴
+        //        ConnectServer(connection.IP, connection.Port);
+        //        attempts--;
+        //    } while (!socket.Connected && attempts > 0);
+        //}
+        #endregion
+
+        /// <summary>
+        /// 閲嶈繛
+        /// </summary>
+        public void HandleDisconnection()
         {
-            int attempts = 5;
-            do
+            int maxAttempts = 10; // 鏈�澶у皾璇曟鏁�
+            int currentAttempts = 0;
+
+            while (currentAttempts < maxAttempts)
             {
-                string message = "杩炴帴宸叉柇寮�..." + '\n';
+                string message = "涓嶩ost绯荤粺杩炴帴宸叉柇寮�..." + '\n';
                 message += "绛夊緟5绉掑悗閲嶆柊杩炴帴" + '\n';
                 Console.WriteLine(message);
 
@@ -233,16 +286,51 @@
 
                 // 灏濊瘯閲嶆柊杩炴帴
                 ConnectServer(connection.IP, connection.Port);
-                attempts--;
-            } while (!socket.Connected && attempts > 0);
-        }
-        public void clientSend(byte[] buffer)
-        {
-            var Y = Encoding.UTF8.GetString(buffer);
-            LogFactory.GetLog("Socket鍙戦�佹暟鎹�").Info(true, Y);
-            socket.Send(buffer);
+                currentAttempts++;
+
+                // 妫�鏌ユ槸鍚﹀凡杩炴帴
+                if (socket?.Connected ?? false)
+                {
+                    break; // 杩炴帴鎴愬姛锛岄��鍑哄惊鐜�
+                }
+            }
+
+            if (currentAttempts >= maxAttempts)
+            {
+                Console.WriteLine("宸茶揪鍒版渶澶ч噸杩炴鏁帮紝鍋滄閲嶈繛銆�");
+                // 鍙互鍦ㄨ繖閲岃繘琛屽叾浠栧鐞嗭紝渚嬪閫氱煡鐢ㄦ埛鎴栬褰曟棩蹇�
+            }
         }
 
+        /// <summary>
+        /// 涓嬪彂
+        /// </summary>
+        /// <param name="buffer"></param>
+        public void clientSend(byte[] buffer)
+        {
+            socket.Send(buffer);
+
+
+            int newLength = buffer.Length - 2;
+            byte[] newArray = new byte[newLength];
+
+            Array.Copy(buffer, 1, newArray, 0, newLength);
+            string calculatedChecksum = GetCheckSumone(newArray);
+
+            var str = Encoding.UTF8.GetString(newArray);
+            string receivedChecksum = str.Substring(str.Length - 2);
+
+            var x = Encoding.UTF8.GetString(newArray);
+
+            LogFactory.GetLog("Socket鍙戦�佹暟鎹�").Info(true, $"{JsonConvert.SerializeObject(GetParse(x))}{Environment.NewLine}");
+        }
+
+        /// <summary>
+        /// CheckSum瑙f瀽
+        /// </summary>
+        /// <param name="x"></param>
+        /// <returns></returns>
+        /// <exception cref="Exception"></exception>
         public string GetCheckSumone(byte[] x)
         {
             int sum = 0;
@@ -270,6 +358,10 @@
         /// 浣滀笟浠诲姟ID  棰勭暀
         /// </summary>
         public const string JobOrderID = "0000000000000000";
+
+        public const string JobOrderIDPDA = "PDA0000000000000";
+
+        public const string JobOrderIDF   = "FIRE000000000000";
 
         /// <summary>
         /// 浼樺厛绾�  棰勭暀
@@ -360,7 +452,7 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("DeviceRequestInbound").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
         }
 
@@ -378,7 +470,7 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("RequestCommunication").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
         }
 
@@ -396,7 +488,7 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("JobReady").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
 
         }
@@ -415,7 +507,7 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("DeviceStateReport").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
 
         }
@@ -429,14 +521,13 @@
         {
             try
             {
-                string str = SendNotReply + "917" + BaseDal.GetSeqNo().Result.ToString("D5") + Status;
+                string str = SendandReply + "917" + BaseDal.GetSeqNo().Result.ToString("D5") + Status;
                 clientSend(MakeStringToByteMsg(str));
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("DeviceAutoStatusReport").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
-
         }
 
         /// /// <summary>
@@ -456,7 +547,7 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("JobStartOrEnd").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
 
         }
@@ -479,7 +570,7 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("PalletActionReport宸ュ簭907").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
 
         }
@@ -508,7 +599,35 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("PalletActionReport宸ュ簭901").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
+
+        }
+
+        public void PalletActionReportPDA(string FormLocation, string ToLocation, string TaskType, string PallteCode)
+        {
+            try
+            {
+                string str = SendandReply + "901" + BaseDal.GetSeqNo().Result.ToString("D5") + "0" + JobOrderIDPDA + priority + FormLocation + ToLocation + TaskType + TrayCnt + PallteCode;
+                clientSend(MakeStringToByteMsg(str));
+            }
+            catch (Exception ex)
+            {
+                LogFactory.GetLog("PalletActionReportPDA宸ュ簭901").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
+
+        }
+
+        public void PalletActionReportFrie(string FormLocation, string ToLocation, string TaskType, string PallteCode)
+        {
+            try
+            {
+                string str = SendandReply + "901" + BaseDal.GetSeqNo().Result.ToString("D5") + "0" + JobOrderIDF + priority + FormLocation + ToLocation + TaskType + TrayCnt + PallteCode;
+                clientSend(MakeStringToByteMsg(str));
+            }
+            catch (Exception ex)
+            {
+                LogFactory.GetLog("PalletActionReportPDA宸ュ簭901").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
 
         }
@@ -533,7 +652,7 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("DeviceStationStatusReport").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
 
         }
@@ -549,6 +668,7 @@
         {
             try
             {
+                ErrorReport(Restocking, "A", "00");
                 string str = SendandReply + "105" + BaseDal.GetSeqNo().Result.ToString("D5") + "R" + JobOrderID + priority + FormLocation + ToLocation + TaskType + TrayCnt + PallteCode;
                 Dt_HostLog hostLog = new Dt_HostLog()
                 {
@@ -561,9 +681,26 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("RecreateGetLocation").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
 
+        }
+
+        /// <summary>
+        /// CheckSum鏍¢獙 宸ュ簭981
+        /// </summary>
+        /// <param name="message"></param>
+        public void CheckSum(string message)
+        {
+            try
+            {
+                string str = SendNotReply + "981" + BaseDal.GetSeqNo().Result.ToString("D5") + message;
+                clientSend(MakeStringToByteMsg(str));
+            }
+            catch (Exception ex)
+            {
+                LogFactory.GetLog("CheckSum").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
         }
 
         /// /// <summary>
@@ -581,9 +718,8 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("ErrorReport").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
-
         }
 
         /// <summary>
@@ -600,7 +736,7 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("DeviceReceiveJobResponse").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
 
         }
@@ -616,6 +752,7 @@
         {
             try
             {
+                ErrorReport(EmptyOutBoundconst, "A", "00");
                 string str = SendandReply + "107" + BaseDal.GetSeqNo().Result.ToString("D5") + "1" + JobOrderID + priority + FormLocation + ToLocation + "O" + TrayCnt + PallteCode;
                 Dt_HostLog hostLog = new Dt_HostLog()
                 {
@@ -628,7 +765,7 @@
             }
             catch (Exception ex)
             {
-                throw new Exception(ex.Message);
+                LogFactory.GetLog("EmptyOutBound").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
 
         }
@@ -639,8 +776,63 @@
         /// <param name="AgvStatus"></param>
         public void DeviceStatusReportResponse(HOSTAGVStatus AgvStatus, string X, string Y)
         {
-            string str = SendNotReply + "910" + BaseDal.GetSeqNo().Result.ToString("D5") + GetFieldsAsString(AgvStatus) + X + Y;
-            clientSend(MakeStringToByteMsg(str));
+            try
+            {
+                string str = SendNotReply + "910" + BaseDal.GetSeqNo().Result.ToString("D5") + GetFieldsAsString(AgvStatus) + X + Y;
+                clientSend(MakeStringToByteMsg(str));
+                Dt_HostLog hostLog = new Dt_HostLog()
+                {
+                    CommandID = 910,
+                    Count = 0,
+                    Messgae = str,
+                };
+                _hostLogRepository.AddData(hostLog);
+            }
+            catch (Exception ex)
+            {
+                LogFactory.GetLog("DeviceStatusReportResponse").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
+        }
+
+        /// <summary>
+        /// 鍥炲HOST987宸ュ簭  宸ュ簭988
+        /// </summary>
+        /// <param name="AgvStatus"></param>
+        /// <param name="X"></param>
+        /// <param name="Y"></param>
+        public void FireAlarmReportResponse(string SeqNo,string IsOK,string Location)
+        {
+            try
+            {
+                string str = SendNotReply + "988" + SeqNo + IsOK + Location;
+                clientSend(MakeStringToByteMsg(str));
+            }
+            catch (Exception ex)
+            {
+                LogFactory.GetLog("FireAlarmReportResponse").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
+            
+        }
+
+
+        /// <summary>
+        /// 鍥炲HOST301宸ュ簭  宸ュ簭302
+        /// </summary>
+        /// <param name="AgvStatus"></param>
+        /// <param name="X"></param>
+        /// <param name="Y"></param>
+        public void UpdateLocalTimeResponse(string message,string SeqNo)
+        {
+            try
+            {
+                string str = SendNotReply + "302" + SeqNo + message;
+                clientSend(MakeStringToByteMsg(str));
+            }
+            catch (Exception ex)
+            {
+                LogFactory.GetLog("UpdateLocalTimeResponse").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
+
         }
 
         #endregion
@@ -653,59 +845,44 @@
         /// <param name="message"></param>
         public void ReceiveCommandResponse(string message)
         {
-            var parseMessage = GetParse(message);
-            var lcationEnd = parseMessage.body.ToLocation;
-            switch (parseMessage.body.ret)
+            try
             {
-                //OK
-                case "0":
-                    //var location = _locationRepository.QueryFirst(x => x.LocationCode == lcationEnd);
-                    var location = SqlSugarHelper.DbWMS.Queryable<DtLocationInfo>().Where(x => x.LocationCode == parseMessage.body.ToLocation).First();
-                    if (location == null)
-                    {
-                        return;
-                    }
-                    if (location.LocationStatus == (int)LocationEnum.Free)
-                    {
-                        var task = InsertWMSTask(parseMessage);
-                        Thread.Sleep(500);
-                        InsertAGVTask(task);
-                        location.LocationStatus = 1;
-                        //SqlSugarHelper.DbWMS.Insertable(task).ExecuteCommand();
-                        SqlSugarHelper.DbWMS.Updateable(location).ExecuteCommand();
-                        BaseDal.AddData(task);
-                        //915
-                        JobReady("0");
-                        return;
-                    }
-                    else
-                    {
-                        ErrorReport(Restocking, "A", "00");
-                        Thread.Sleep(500);
-                        RecreateGetLocation(parseMessage.body.FromLocation, parseMessage.body.ToLocation, parseMessage.body.JobType, parseMessage.body.TrayIdList.Substring(0, 10));
-                        //todo璐т綅鏈夎揣閲嶅鍏ュ簱
-                        return;
-                    }
-                //NG
-                case "1":
-                    break;
-                //鏃犲簱浣嶅垎閰�
-                case "2":
-                    break;
-                //绔欏彴鍒扮珯鍙帮紝鍑哄簱绔欏彴鏈噯澶囧ソ
-                case "3":
-                    break;
-                //闈炲父娓╁伐绋�
-                case "4":
-                    break;
-
-                case "9":
-                    break;
-                default:
-                    break;
+                ParseMessage parseMessage = GetParse(message);
+                var lcationEnd = parseMessage.body.ToLocation;
+                switch (parseMessage.body.ret)
+                {
+                    //OK
+                    case "0":
+                        GetLocation(parseMessage);
+                        break;
+                    //NG
+                    case "1":
+                        AddErrorMessage("2013", "Host", StationParse(parseMessage.body.FromLocation));
+                        break;
+                    //鏃犲簱浣嶅垎閰�
+                    case "2":
+                        AddErrorMessage("2014", "Host", StationParse(parseMessage.body.FromLocation));
+                        break;
+                    //绔欏彴鍒扮珯鍙帮紝鍑哄簱绔欏彴鏈噯澶囧ソ
+                    case "3":
+                        AddErrorMessage("2015", "Host", StationParse(parseMessage.body.FromLocation));
+                        break;
+                    //闈炲父娓╁伐绋�
+                    case "4":
+                        AddErrorMessage("2016", "Host", StationParse(parseMessage.body.FromLocation));
+                        break;
+                    case "9":
+                        AddErrorMessage("2017", "Host", StationParse(parseMessage.body.FromLocation));
+                        break;
+                    default:
+                        break;
+                }
             }
-
-            LogFactory.GetLog("Host102鍥炲WMS101").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(parseMessage)}{Environment.NewLine}", "");
+            catch (Exception ex)
+            {
+                ErrorReport("2199", "A", "00");
+                LogFactory.GetLog("Host102鍥炲WMS101ReceiveCommandResponse").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }         
         }
 
         /// <summary>
@@ -713,28 +890,41 @@
         /// </summary>
         public void AGVJobStartOrEndResponse(string status, string message)
         {
-            switch (message)
+            try
             {
-                //OK
-                case "0":
-                    if (status == "E")
-                    {
-                        DeviceStateReport("I");
-                        Thread.Sleep(3000);
-                        JobReady("1");
-                    }
-                    break;
-                //NG
-                case "1":
-                    //璋冪敤AGV鏆傚仠鎺ュ彛
-                    break;
-                case "9":
-                    break;
-                default:
-                    break;
-            }
+                switch (message)
+                {
+                    //OK
+                    case "0":
+                        if (status == "E")
+                        {
+                            AGVStatusRespone Agvstatus = GetAGVStatus();
 
-            LogFactory.GetLog("Host906鍥炲WMS905").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(status)}{Environment.NewLine}{JsonConvert.SerializeObject(message)}{Environment.NewLine}", "");
+                            DeviceStateReport(GetAGVStatus(Agvstatus.RuntimeStatus));
+                            Thread.Sleep(3000);
+                            JobReady("1");
+                        }
+                        break;
+                    //NG
+                    case "1":
+                        //璋冪敤AGV鏆傚仠鎺ュ彛
+                        AddErrorMessage("2004", "Host", "");
+                        break;
+                    case "9":
+                        AddErrorMessage("2005", "Host", "");
+                        break;
+                    default:
+                        break;
+                }
+            }
+            catch (Exception ex)
+            {
+                ErrorReport("2199", "A", "00");
+                LogFactory.GetLog("Host906鍥炲WMS905AGVJobStartOrEndResponse").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
+           
+
+            
         }
 
         /// <summary>
@@ -742,44 +932,31 @@
         /// </summary>
         public void DataReportResponse(string message)
         {
-            LogFactory.GetLog("Host902鍥炲WMS901").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(message)}{Environment.NewLine}", "");
-            #region 
-            //Dt_Task task = BaseDal.QueryFirst(x => (x.TaskState == (int)TaskOutStatusEnum.AGV_OutFinish || x.TaskState == (int)TaskRelocationStatusEnum.AGV_RelocationFinish || x.TaskState == (int)TaskInStatusEnum.AGV_InFinish) && x.Roadway != "PDA");
-            //if (task != null)
-            //{
-            //    switch (task.TaskType)
-            //    {
-            //        case 200:
-            //            //鍏ュ簱
-            //            if (message == "0")
-            //            {
-            //                JobStartOrEnd("E", task.Remark, task.TargetAddress, "O", task.PalletCode);
-            //            }
-            //            break;
-            //        case 100:
-            //            //鍑哄簱
-            //            if (message == "0")
-            //            {
-            //                JobStartOrEnd("E", task.SourceAddress, task.Remark, "O", task.PalletCode);
-            //            }
-            //            break;
-            //        case 300:
-            //            if (message == "0")
-            //            {
-            //                JobStartOrEnd("E", task.SourceAddress, task.TargetAddress, "O", task.PalletCode);
-            //            }
-            //            _taskService.CompleteRelocationboundTask(task);
-            //            break;
-            //        case 400:
-            //            if (message == "0")
-            //            {
-            //                JobStartOrEnd("E", task.Remark, task.HostName, "O", task.PalletCode);
-            //            }
-            //            break;
-            //        default:
-            //            break;
-            //    }
-            //}
+            try
+            {
+                DeleteHostLog(901);
+                #region 
+                switch (message)
+                {
+                    case "0":
+
+                        break;
+                    case "1":
+                        AddErrorMessage("2001", "Host", "");
+                        break;
+                    case "9":
+                        AddErrorMessage("2002", "Host", "");
+                        break;
+                    default:
+                        break;
+                }
+            }
+            catch (Exception ex)
+            {
+                ErrorReport("2199", "A", "00");
+                LogFactory.GetLog("Host902鍥炲WMS901DataReportResponse").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
+            
             #endregion
         }
         /// <summary>
@@ -795,48 +972,19 @@
                 {
                     //OK
                     case "0":
-                        var location = SqlSugarHelper.DbWMS.Queryable<DtLocationInfo>().Where(x => x.LocationCode == parseMessage.body.FromLocation).First();
-                        if (location == null)
-                        {
-                            return;
-                        }
-                        if (location.LocationStatus == (int)LocationEnum.InStock)
-                        {
-                            Dt_Task task = InsertWMSTask(parseMessage);
-                            //BaseDal.AddData(task);
-                            location.LocationStatus = 1;
-                            SqlSugarHelper.DbWMS.Insertable(task).ExecuteCommand();
-                            SqlSugarHelper.DbWMS.Updateable(location).ExecuteCommand();
-                            InsertAGVTask(task);
-                            //Thread.Sleep(500);
-                            //915
-                            JobReady("0");
-                            Thread.Sleep(500);
-                            //104
-                            DeviceReceiveJobResponse("0");
-                        }
-                        else
-                        {
-                            ErrorReport(EmptyOutBoundconst, "A", "00");
-                            Thread.Sleep(500);
-                            EmptyOutBound(parseMessage.body.FromLocation, parseMessage.body.ToLocation, parseMessage.body.TrayIdList.Substring(0, 10));
-                            return;
-                        }
-
+                        GetLocation(parseMessage);
                         break;
                     default:
                         break;
                 }
-                LogFactory.GetLog("Host103").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(parseMessage)}{Environment.NewLine}", "");
-
             }
             catch (Exception ex)
             {
-                DeviceReceiveJobResponse("1");
+                ErrorReport("2199", "A", "00");
+                LogFactory.GetLog("Host103HOSTOutBoundTask").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
 
         }
-
         /// <summary>
         /// HOST璁惧鐘舵�佽幏鍙�  宸ュ簭935
         /// </summary>
@@ -849,6 +997,12 @@
 
                 StationStatus stationIn = GetStationStatus("B002");
                 StationStatus stationOut = GetStationStatus("B001");
+
+                if(stationIn == null || stationOut == null)
+                {
+                    ErrorReport("2103", "A", "00");
+                }
+
                 List<OutStationStatus> outStationStatus = GetOutStationStatus(stationOut);
                 List<InStationStatus> inStationStatus = GetInStationStatus(stationIn);
 
@@ -889,7 +1043,6 @@
                 {
                     RuntimeStatus = CapitalizeFirstLetter(status.RuntimeStatus),
                     AutoStatus = status.AutoStatus == "MaintenanceMode" ? "1" : "0",
-                    //Ready = status.AutoStatus == "MaintenanceMode" ? "0" : "1",
                 };
                 if (status.RuntimeStatus == "Idle" && status.AutoStatus == "ControlMode")
                 {
@@ -901,12 +1054,13 @@
                 }
                 DeviceStationStatusReport(AgvStatus, outStationStatus, inStationStatus, sSeqNo);
             }
-            catch (Exception)
+            catch (Exception ex)
             {
-                DeviceReceiveJobResponse("1");
+                ErrorReport("2199", "A", "00");
+                LogFactory.GetLog("Host935DeviceStationStatusInvite").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+                JobReady("1");
             }
 
-            LogFactory.GetLog("Host935").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(sSeqNo)}{Environment.NewLine}", "");
         }
 
         /// <summary>
@@ -917,73 +1071,35 @@
         {
             try
             {
+                DeleteHostLog(105);
                 var parseMessage = GetParse(message);
                 var lcationEnd = parseMessage.body.ToLocation;
                 switch (parseMessage.body.ret)
                 {
                     //OK
                     case "0":
-                        var location = SqlSugarHelper.DbWMS.Queryable<DtLocationInfo>().Where(x => x.LocationCode == parseMessage.body.ToLocation).First();
-                        if (location == null)
-                        {
-                            ErrorReport("2102", "A", "00");
-                            Thread.Sleep(500);
-                            RecreateGetLocation(parseMessage.body.FromLocation, parseMessage.body.ToLocation, parseMessage.body.JobType, parseMessage.body.TrayIdList.Substring(0, 10));
-                            return;
-                        }
-                        if (location.LocationStatus == (int)LocationEnum.Free)
-                        {
-                            var task = SqlSugarHelper.DbWMS.Queryable<Dt_Task>().Where(x => x.PalletCode == parseMessage.body.TrayIdList.Substring(0, 10)).First();
-                            if (task == null)
-                            {
-                                location.LocationStatus = (int)LocationEnum.Lock;
-                                var tasknew = InsertWMSTask(parseMessage);
-                                InsertAGVTask(tasknew);
-                                BaseDal.AddData(tasknew);
-                                SqlSugarHelper.DbWMS.Updateable(location);
-                                Thread.Sleep(500);
-                                //915
-                                JobReady("0");
-                            }
-                            else
-                            {
-                                var Agvtask = SqlSugarHelper.DbAGV.Queryable<task_call>().Where(x => x.d_involed5 == task.TaskNum.ToString()).First();
-                                location.LocationStatus = (int)LocationEnum.Lock;
-                                task.TargetAddress = lcationEnd;
-                                Agvtask.d_involed2 = lcationEnd;
-                                SqlSugarHelper.DbWMS.Updateable(task);
-                                SqlSugarHelper.DbWMS.Updateable(location);
-                                SqlSugarHelper.DbAGV.Updateable(Agvtask);
-                                Thread.Sleep(500);
-                                //915
-                                JobReady("0");
-                            }
-                            return;
-                        }
-                        else
-                        {
-                            ErrorReport(Restocking, "A", "00");
-                            Thread.Sleep(500);
-                            RecreateGetLocation(parseMessage.body.FromLocation, parseMessage.body.ToLocation, parseMessage.body.JobType, parseMessage.body.TrayIdList.Substring(0, 10));
-                            return;
-                        }
+                        GetLocation(parseMessage,true);
+                        break;
                     //NG
                     case "1":
+                        AddErrorMessage("2019", "Host", StationParse(parseMessage.body.FromLocation));
                         break;
                     //鏃犲簱浣嶅垎閰�
                     case "2":
+                        AddErrorMessage("2020", "Host", StationParse(parseMessage.body.FromLocation));
                         break;
                     case "9":
+                        AddErrorMessage("2021", "Host", StationParse(parseMessage.body.FromLocation));
                         break;
                     default:
                         break;
                 }
-
-                LogFactory.GetLog("Host106閲嶆柊鍒嗛厤搴撲綅").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(parseMessage)}{Environment.NewLine}", "");
             }
-            catch (Exception)
+            catch (Exception ex)
             {
-                DeviceReceiveJobResponse("1");
+                ErrorReport("2199", "A", "00");
+                LogFactory.GetLog("Host106閲嶆柊鍒嗛厤搴撲綅RecreateGetLocation").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+                JobReady("1");
             }
         }
 
@@ -993,41 +1109,196 @@
         /// <param name="message"></param>
         public void EmptyOutBoundResponse(string message)
         {
-            if (message != null && message == "0")
+            try
             {
-                DeviceStateReport("I");
-                Thread.Sleep(2000);
-                JobReady("1");
+                DeleteHostLog(107);
+                if (message != null)
+                {
+                    switch (message)
+                    {
+                        case "0":
+                            AGVStatusRespone Agvstatus = GetAGVStatus();
+                            DeviceStateReport(GetAGVStatus(Agvstatus.RuntimeStatus));
+                            Thread.Sleep(2000);
+                            JobReady("1");
+                            break;
+                        case "1":
+                            AddErrorMessage("2023", "Host", "");
+                            break;
+                        case "9":
+                            AddErrorMessage("2024", "Host", "");
+                            break;
+                        default:
+                            break;
+                    }
+                }
             }
-            LogFactory.GetLog("Host108绌哄嚭搴撳搷搴�").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(message)}{Environment.NewLine}", "");
+            catch (Exception ex)
+            {
+                ErrorReport("2199", "A", "00");
+                LogFactory.GetLog("Host108绌哄嚭搴撳搷搴擡mptyOutBoundResponse").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
         }
 
+        /// <summary>
+        /// Host涓嬪彂鐏浠诲姟  987
+        /// </summary>
+        public void FireAlarm(string Location, string SeqNo)
+        {
+            try
+            {
+                Dt_Task taskNew = new Dt_Task();
+                var stock = SqlSugarHelper.DbWMS.Queryable<DtStockInfo>().Where(x => x.LocationCode == Location).First();
+
+                var location = SqlSugarHelper.DbWMS.Queryable<Dt_Task>().Where(x => x.SourceAddress == Location).First();
+                if (location != null)
+                {
+                    FireAlarmReportResponse(SeqNo, "0", Location);
+                    return;
+                }
+                var stationOne = SqlSugarHelper.DbWMS.Queryable<Dt_Task>().Where(x => x.TargetAddress == "B001::1").ToList();
+                var stationTwo = SqlSugarHelper.DbWMS.Queryable<Dt_Task>().Where(x => x.TargetAddress == "B001::2").ToList();
+
+                if (stationOne.Count > 0 && stationTwo.Count > 0)
+                {
+                    if (stationOne.Count > stationTwo.Count)
+                    {
+                        taskNew = GetFireAlarm(Location, "B001::2", stock == null ? "F" + DateTime.Now.ToString("HHmmss") + new Random().Next(100, 1000) : stock.PalletCode, SeqNo);
+                    }
+                    else
+                    {
+                        taskNew = GetFireAlarm(Location, "B001::1", stock == null ? "F" + DateTime.Now.ToString("HHmmss") + new Random().Next(100, 1000) : stock.PalletCode, SeqNo);
+                    }
+                    FireAlarmReportResponse(SeqNo, "0", Location);
+                }
+                else
+                {
+                    StationStatus stationOut = GetStationStatus("B001");
+
+                    if (stationOut != null && stationOut.WorkstationO == "0" && stationOne.Count == 0)
+                    {
+                        taskNew = GetFireAlarm(Location, "B001::1", stock == null ? "F" + DateTime.Now.ToString("HHmmss") + new Random().Next(100, 1000) : stock.PalletCode, SeqNo);
+                    }
+                    else if (stationOut != null && stationOut.WorkstationT == "0" && stationTwo.Count == 0)
+                    {
+                        taskNew = GetFireAlarm(Location, "B001::2", stock == null ? "F" + DateTime.Now.ToString("HHmmss") + new Random().Next(100, 1000) : stock.PalletCode, SeqNo);
+                    }
+                    else
+                    {
+                        taskNew = GetFireAlarm(Location, "B001::2", stock == null ? "F" + DateTime.Now.ToString("HHmmss") + new Random().Next(100, 1000) : stock.PalletCode, SeqNo);
+                    }
+                    FireAlarmReportResponse(SeqNo, "0", Location);
+                }
+                BaseDal.AddData(taskNew);
+                InsertAGVTask(taskNew);
+            }
+            catch (Exception ex)
+            {
+                ErrorReport("2199", "A", "00");
+                LogFactory.GetLog("鐏987FireAlarm").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
+        }
+
+
+        /// <summary>
+        /// 鑾峰彇娑堥槻浠诲姟
+        /// </summary>
+        /// <param name="SourceAddress">璧峰鍦板潃</param>
+        /// <param name="TargetAddress">缁堢偣鍦板潃</param>
+        /// <param name="PalletCode">鎵樼洏鍙�</param>
+        /// <param name="SeqNo">Host搴忓垪鍙�</param>
+        /// <returns></returns>
+        public Dt_Task GetFireAlarm(string SourceAddress, string TargetAddress, string PalletCode, string SeqNo)
+        {
+            return new Dt_Task()
+            {
+                SourceAddress = SourceAddress,
+                TargetAddress = TargetAddress,
+                CurrentAddress = SourceAddress,
+                NextAddress = TargetAddress,
+                TaskType = (int)TaskFireAlarmTypeEnum.FireAlarmOut,
+                TaskState = (int)TaskFireAlarmStatusEnum.FireAlarmNew,
+                Remark = TargetAddress,
+                TaskNum = BaseDal.GetTaskNo().Result,
+                PalletCode = PalletCode == null ? "" : PalletCode,
+                Dispatchertime = DateTime.Now,
+                Grade = 1,
+                SeqNo = Convert.ToInt32(SeqNo),
+                CommandID = Convert.ToInt32(987),
+            };
+        }
+       
         /// <summary>
         /// HOST鑾峰彇璁惧鐘舵��  宸ュ簭909
         /// </summary>
         public void DeviceStatusReportRequest()
         {
-            AGVStatusRespone status = GetAGVStatus();
-
-            HOSTAGVStatus AgvStatus = new HOSTAGVStatus()
+            try
             {
-                RuntimeStatus = CapitalizeFirstLetter(status.RuntimeStatus),
-                AutoStatus = status.AutoStatus == "MaintenanceMode" ? "1" : "0",
+                DeleteHostLog(910);
+                AGVStatusRespone status = GetAGVStatus();
 
-            };
-            if (status.RuntimeStatus == "Idle" && status.AutoStatus == "ControlMode")
-            {
-                AgvStatus.Ready = "1";
+                HOSTAGVStatus AgvStatus = new HOSTAGVStatus()
+                {
+                    RuntimeStatus = CapitalizeFirstLetter(status.RuntimeStatus),
+                    AutoStatus = status.AutoStatus == "MaintenanceMode" ? "1" : "0",
+
+                };
+                if (status.RuntimeStatus == "Idle" && status.AutoStatus == "ControlMode")
+                {
+                    AgvStatus.Ready = "1";
+                }
+                else
+                {
+                    AgvStatus.Ready = "0";
+                }
+                string axis = "000000";
+
+                DeviceStatusReportResponse(AgvStatus, axis, axis);
             }
-            else
+            catch (Exception ex)
             {
-                AgvStatus.Ready = "0";
+                ErrorReport("2199", "A", "00");
+                LogFactory.GetLog("Host蹇冭烦").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
             }
-            string axis = "000000";
+            
+        }
 
-            DeviceStatusReportResponse(AgvStatus, axis, axis);
 
-            LogFactory.GetLog("Host蹇冭烦").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(AgvStatus)}{Environment.NewLine}{JsonConvert.SerializeObject(status)}{Environment.NewLine}", "");
+        /// <summary>
+        /// WMS鍚屾Host鏃堕棿  宸ュ簭301
+        /// </summary>
+        public void UpdateLocalTime(string Time,string SeqNo)
+        {
+            try
+            {
+                SYSTEMTIME newTime = new SYSTEMTIME
+                {
+                    Year = Convert.ToUInt16(Time.Substring(0,4)),
+                    Month = Convert.ToUInt16(Time.Substring(4, 2)),
+                    Day = Convert.ToUInt16(Time.Substring(6, 2)),
+                    Hour = Convert.ToUInt16(Time.Substring(8, 2)),
+                    Minute = Convert.ToUInt16(Time.Substring(10, 2)),
+                    Second = Convert.ToUInt16(Time.Substring(12, 2)),
+                    Milliseconds = 0
+                };
+                if (SetLocalTime(ref newTime))
+                {
+                    UpdateLocalTimeResponse("0", SeqNo);
+                    Console.WriteLine("绯荤粺鏃堕棿宸叉垚鍔熶慨鏀广��");
+                }
+                else
+                {
+                    UpdateLocalTimeResponse("1", SeqNo);
+                    Console.WriteLine("淇敼绯荤粺鏃堕棿澶辫触銆傝纭繚浠ョ鐞嗗憳鏉冮檺杩愯姝ょ▼搴忋��");
+                }
+            }
+            catch (Exception ex)
+            {
+                ErrorReport("2199", "A", "00");
+                LogFactory.GetLog("UpdateLocalTime鏃堕棿鍚屾").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(ex.Message)}{Environment.NewLine}{ex.StackTrace}", "");
+            }
+
         }
         #endregion
 
@@ -1065,8 +1336,6 @@
                 // 澶嶅埗鍘熷鏁扮粍鐨勬墍鏈夋暟鎹埌鏂版暟缁勭殑涓棿閮ㄥ垎
                 Array.Copy(buffer, 0, newArray, 1, buffer.Length);
 
-                //var parseMessage = GetParse(str);
-                LogFactory.GetLog("Socket鍙戦�佹姤鏂�").Info(true, str);
                 return newArray;
             }
             catch (Exception ex)
@@ -1177,66 +1446,15 @@
             });
             return inStationStatus;
         }
-        public ParseMessage SubString(string Y)
-        {
-
-            const string STX = "0x02";
-            const string ETX = "0x03";
-
-            // 妫�鏌ユ槸鍚︿互 STX 寮�澶淬�丒TX 缁撳熬
-            if (Y.Substring(0, 4) == STX && Y.Substring(Y.Length - 4) == ETX)
-            {
-                string str = Y.Substring(4, Y.Length - 8);
-                byte[] message = Encoding.UTF8.GetBytes(str);
-                int newLength = message.Length - 2;
-
-                if (newLength < 0)
-                {
-                    throw new ArgumentException("鏁扮粍闀垮害涓嶈冻锛屾棤娉曞幓鎺夋渶鍚庝袱浣嶃��");
-                }
-
-                byte[] newArray = new byte[newLength];
-                Array.Copy(message, 0, newArray, 0, newLength);
-                string calculatedChecksum = GetCheckSum(newArray);
-
-                string receivedChecksum = str.Substring(str.Length - 2);
-
-                if (calculatedChecksum == receivedChecksum)
-                {
-                    var x = Encoding.UTF8.GetString(newArray);
-                    ParseMessage parseMessage = new ParseMessage()
-                    {
-                        bDir = x.Substring(0, 1),
-                        bObjID = x.Substring(2, 10),
-                        bReply = x.Substring(11, 1),
-                        bCmdID = x.Substring(12, 3),
-                        nSeqNo = x.Substring(15, 5),
-                        //Body = x.Substring(21),
-                    };
-                    return parseMessage;
-                }
-                else
-                {
-                    Console.WriteLine("鏍¢獙澶辫触锛�");
-                    return null;
-                }
-            }
-            else
-            {
-                Console.WriteLine("鏃犳晥鎶ユ枃鏍煎紡锛�");
-                return null;
-            }
-        }
-        #endregion
-
-        #region 瀹氫箟瀵硅薄
-
-
         #endregion
 
         #region 绉佹湁鏂规硶
-
-        private Dt_Task InsertWMSTask(ParseMessage parseMessage)
+        /// <summary>
+        /// 娣诲姞WMS浠诲姟
+        /// </summary>
+        /// <param name="parseMessage"></param>
+        /// <exception cref="Exception"></exception>
+        private void InsertWMSTask(ParseMessage parseMessage)
         {
             int taskType = 0;
             int taskState = 0;
@@ -1244,9 +1462,9 @@
             if (parseMessage.body.JobType == "I")
             {
                 Dt_StationManager Instation = _stationManagerRepository.QueryFirst(x => x.HostName == parseMessage.body.FromLocation.Substring(4, 2));
-                task.SourceAddress = Instation.stationName;
+                task.SourceAddress = StationParse(parseMessage.body.FromLocation);
                 task.TargetAddress = parseMessage.body.ToLocation;
-                task.CurrentAddress = Instation.stationName;
+                task.CurrentAddress = StationParse(parseMessage.body.FromLocation);
                 task.NextAddress = parseMessage.body.ToLocation;
                 taskType = (int)TaskInboundTypeEnum.Inbound;
                 taskState = (int)TaskInStatusEnum.InNew;
@@ -1256,33 +1474,38 @@
             else if (parseMessage.body.JobType == "O")
             {
                 task.SourceAddress = parseMessage.body.FromLocation;
-                Dt_StationManager Instation = _stationManagerRepository.QueryFirst(x => x.HostName == parseMessage.body.ToLocation.Substring(4, 2));
-                task.TargetAddress = Instation.stationName;
+                task.TargetAddress = StationParse(parseMessage.body.ToLocation);
                 task.CurrentAddress = parseMessage.body.FromLocation;
-                task.NextAddress = Instation.stationName;
+                task.NextAddress = StationParse(parseMessage.body.ToLocation);
                 taskType = (int)TaskOutboundTypeEnum.Outbound;
+                taskState = (int)TaskOutStatusEnum.OutNew;
+                task.Remark = parseMessage.body.ToLocation;
+            }
+            else if (parseMessage.body.JobType == "C")
+            {
+                task.SourceAddress = parseMessage.body.FromLocation;
+                task.TargetAddress = StationParse(parseMessage.body.ToLocation);
+                task.CurrentAddress = parseMessage.body.FromLocation;
+                task.NextAddress = StationParse(parseMessage.body.ToLocation);
+                taskType = (int)TaskOutboundTypeEnum.OutQuality;
                 taskState = (int)TaskOutStatusEnum.OutNew;
                 task.Remark = parseMessage.body.ToLocation;
             }
             else if (parseMessage.body.JobType == "S")
             {
-                Dt_StationManager stationone = _stationManagerRepository.QueryFirst(x => x.HostName == parseMessage.body.FromLocation.Substring(4, 2));
-                Dt_StationManager stationtwo = _stationManagerRepository.QueryFirst(x => x.HostName == parseMessage.body.ToLocation.Substring(4, 2));
                 taskType = (int)TaskStationTypeEnum.StationToStation;
                 taskState = (int)TaskOutStatusEnum.OutNew;
-                task.SourceAddress = stationone.stationName;
-                task.TargetAddress = stationtwo.stationName;
-                task.CurrentAddress = stationone.stationName;
-                task.NextAddress = stationtwo.stationName;
+                task.SourceAddress = StationParse(parseMessage.body.FromLocation)  ;
+                task.TargetAddress = StationParse(parseMessage.body.ToLocation);
+                task.CurrentAddress = StationParse(parseMessage.body.FromLocation);
+                task.NextAddress = StationParse(parseMessage.body.ToLocation);
                 task.Remark = parseMessage.body.FromLocation;
-                task.HostName = parseMessage.body.ToLocation;
                 task.HostName = parseMessage.body.ToLocation;
             }
             else if (parseMessage.body.JobType == "R")
             {
                 taskType = (int)TaskRelocationTypeEnum.Relocation;
                 taskState = (int)TaskRelocationStatusEnum.RelocationNew;
-
                 task.SourceAddress = parseMessage.body.FromLocation;
                 task.TargetAddress = parseMessage.body.ToLocation;
                 task.CurrentAddress = parseMessage.body.FromLocation;
@@ -1302,8 +1525,118 @@
             task.Grade = 1;
             task.SeqNo = Convert.ToInt32(parseMessage.nSeqNo);
             task.CommandID = Convert.ToInt32(parseMessage.bCmdID);
-            return task;
+            BaseDal.AddData(task);
+            InsertAGVTask(task);
+        }
 
+
+        public void GetLocation(ParseMessage parseMessage,bool repeat=false)
+        {
+
+            switch (parseMessage.body.JobType)
+            {
+                case "I":
+                    var locationIn = SqlSugarHelper.DbWMS.Queryable<DtLocationInfo>().Where(x => x.LocationCode == parseMessage.body.ToLocation).First();
+                    if (locationIn == null)
+                    {
+                        ErrorReport("2102", "A", "00");
+                        return;
+                    }
+                    if (locationIn.LocationStatus == (int)LocationEnum.Free)
+                    {
+                        var taskIn = SqlSugarHelper.DbWMS.Queryable<Dt_Task>().Where(x => x.PalletCode == parseMessage.body.TrayIdList.Substring(0, 10)).First();
+                        if (taskIn != null)
+                        {
+                            _taskService.UpdateTask(StationParse(parseMessage.body.FromLocation), parseMessage.body.ToLocation, parseMessage.body.TrayIdList.Substring(0, 10));
+                        }
+                        else
+                        {
+                            InsertWMSTask(parseMessage);
+                        }
+                        Thread.Sleep(500);
+                        JobReady("0");
+                    }
+                    else
+                    {
+                        RecreateGetLocation(parseMessage.body.FromLocation, parseMessage.body.ToLocation, parseMessage.body.JobType, parseMessage.body.TrayIdList.Substring(0, 10));
+                    }
+                    break;
+                case "O":
+                case "C":
+                    var locationOut = SqlSugarHelper.DbWMS.Queryable<DtLocationInfo>().Where(x => x.LocationCode == parseMessage.body.FromLocation).First();
+                    if (locationOut == null)
+                    {
+                        ErrorReport("2102", "A", "00");
+                        return;
+                    }
+                    if (locationOut.LocationStatus == (int)LocationEnum.InStock)
+                    {
+                        var taskOut = SqlSugarHelper.DbWMS.Queryable<Dt_Task>().Where(x => x.PalletCode == parseMessage.body.TrayIdList.Substring(0, 10)).First();
+                        if (taskOut != null)
+                        {
+                            _taskService.UpdateTask(locationOut.LocationCode, StationParse(parseMessage.body.ToLocation), parseMessage.body.TrayIdList.Substring(0, 10));
+                        }
+                        else
+                        {
+                            InsertWMSTask(parseMessage);
+                        }
+                        Thread.Sleep(500);
+                        JobReady("0");
+                        Thread.Sleep(500);
+                        //104
+                        DeviceReceiveJobResponse("0");
+                    }
+                    else
+                    {
+                        EmptyOutBound(parseMessage.body.FromLocation, parseMessage.body.ToLocation, parseMessage.body.TrayIdList.Substring(0, 10));
+                        _taskService.AddStcokHty(parseMessage.body.TrayIdList.Substring(0, 10), parseMessage.body.FromLocation);
+                    }
+                    break;
+                case "S":
+                    var taskS = SqlSugarHelper.DbWMS.Queryable<Dt_Task>().Where(x => x.PalletCode == parseMessage.body.TrayIdList.Substring(0, 10)).First();
+                    if (taskS != null)
+                    {
+                        _taskService.UpdateTask(StationParse(parseMessage.body.FromLocation), StationParse(parseMessage.body.ToLocation), parseMessage.body.TrayIdList.Substring(0, 10));
+                    }
+                    else
+                    {
+                        InsertWMSTask(parseMessage);
+                    }
+                    Thread.Sleep(500);
+                    JobReady("0");
+
+                    break;
+                case "R":
+                    var locationA = SqlSugarHelper.DbWMS.Queryable<DtLocationInfo>().Where(x => x.LocationCode == parseMessage.body.FromLocation).First();
+                    var locationB = SqlSugarHelper.DbWMS.Queryable<DtLocationInfo>().Where(x => x.LocationCode == parseMessage.body.ToLocation).First();
+                    if (locationA == null || locationB == null)
+                    {
+                        ErrorReport("2102", "A", "00");
+                        return;
+                    }
+                    if (locationA.LocationStatus == (int)LocationEnum.InStock && locationB.LocationStatus == (int)LocationEnum.Free)
+                    {
+                        var taskR = SqlSugarHelper.DbWMS.Queryable<Dt_Task>().Where(x => x.PalletCode == parseMessage.body.TrayIdList.Substring(0, 10)).First();
+                        if (taskR != null)
+                        {
+
+                            _taskService.UpdateTask(parseMessage.body.FromLocation, parseMessage.body.ToLocation, parseMessage.body.TrayIdList.Substring(0, 10));
+                        }
+                        else
+                        {
+                            InsertWMSTask(parseMessage);
+                        }
+                        Thread.Sleep(500);
+                        JobReady("0");
+                    }
+                    else
+                    {
+                        RecreateGetLocation(parseMessage.body.FromLocation, parseMessage.body.ToLocation, parseMessage.body.JobType, parseMessage.body.TrayIdList.Substring(0, 10));
+                    }
+                    break;
+                default:
+                    break;
+            }  
         }
         /// <summary>
         /// 娣诲姞AGV浠诲姟
@@ -1314,59 +1647,137 @@
         {
             string SourceAddress = string.Empty;
             string TargetAddress = string.Empty;
+            string AGVType = string.Empty;
             if (task.TaskType == (int)TaskInboundTypeEnum.Inbound)
             {
                 SourceAddress = task.SourceAddress;
+                AGVType = "2";
                 TargetAddress = InsertHyphenEveryTwoChars(task.TargetAddress);
             }
             else if (task.TaskType == (int)TaskOutboundTypeEnum.Outbound)
             {
                 SourceAddress = InsertHyphenEveryTwoChars(task.SourceAddress);
                 TargetAddress = task.TargetAddress;
+                AGVType = "4";
+            }
+            else if (task.TaskType == (int)TaskOutboundTypeEnum.OutQuality)
+            {
+                SourceAddress = InsertHyphenEveryTwoChars(task.SourceAddress);
+                TargetAddress = task.TargetAddress;
+                AGVType = "128";
             }
             else if (task.TaskType == (int)TaskRelocationTypeEnum.Relocation)
             {
                 TargetAddress = InsertHyphenEveryTwoChars(task.TargetAddress);
                 SourceAddress = InsertHyphenEveryTwoChars(task.SourceAddress);
+                AGVType = "16";
             }
             else if (task.TaskType == (int)TaskStationTypeEnum.StationToStation)
             {
                 TargetAddress = task.TargetAddress;
-                SourceAddress = task.SourceAddress;
+                SourceAddress = InsertHyphenEveryTwoChars(task.SourceAddress);
+                AGVType = "8";
+            }
+            else if (task.TaskType == (int)TaskFireAlarmTypeEnum.FireAlarmOut)
+            {
+                TargetAddress = task.TargetAddress;
+                SourceAddress = InsertHyphenEveryTwoChars(task.SourceAddress);
+                AGVType = "1";
             }
             task_call task_Call = new task_call()
             {
-                d_task_type = task.TaskType == (int)TaskTypeEnum.Inbound ? "1" : "2",
+                d_task_type = AGVType,
                 d_floor = "1",
                 d_involed1 = SourceAddress,
                 d_involed2 = TargetAddress,
                 d_involed5 = task.TaskNum.ToString(),
             };
-
-            return SqlSugarHelper.DbAGV.Insertable(task_Call).ExecuteCommand();
+            var x = SqlSugarHelper.DbAGV.Insertable(task_Call).ExecuteCommand();
+            LogFactory.GetLog("鎻掑叆鏁版嵁鍒癆GV").InfoFormat(true, $"璇锋眰鍙傛暟锛歿JsonConvert.SerializeObject(x)}", "");
+            return x;
         }
         public ParseMessage GetParse(string x)
         {
-            return new ParseMessage()
+            
+            if (string.IsNullOrEmpty(x))
             {
-                bDir = x.Substring(0, 1),
-                bObjID = x.Substring(2, 10),
-                bReply = x.Substring(11, 1),
-                bCmdID = x.Substring(12, 3),
-                nSeqNo = x.Substring(15, 5),
-                body = new ReceiveBody
-                {
-                    ret = x.Substring(20, 1),
-                    JobOrderID = x.Substring(21, 16),
-                    priority = x.Substring(37, 1),
-                    FromLocation = x.Substring(38, 6),
-                    ToLocation = x.Substring(44, 6),
-                    JobType = x.Substring(50, 1),
-                    TrayCnt = x.Substring(51, 1),
-                    TrayIdList = x.Substring(52)
-                },
+                throw new ArgumentNullException(nameof(x), "Input string cannot be null or empty");
+            }
+
+            // 瀹氫箟鎵�鏈夐渶瑕佺殑瀛楁闀垮害鍜屼綅缃�
+            var fieldDefinitions = new (int Start, int Length, string Name)[]
+            {
+                (0, 1, "bDir"),
+                (1, 10, "bObjID"),
+                (11, 1, "bReply"),
+                (12, 3, "bCmdID"),
+                (15, 5, "nSeqNo"),
+                (20, 1, "ret"),
+                (21, 16, "JobOrderID"),
+                (37, 1, "priority"),
+                (38, 6, "FromLocation"),
+                (44, 6, "ToLocation"),
+                (50, 1, "JobType"),
+                (51, 1, "TrayCnt"),
+                (52, x.Length - 52, "TrayIdList") // 鍙彉闀垮害瀛楁
             };
+
+            // 璁$畻鎵�闇�鏈�灏忛暱搴�
+            int minLength = fieldDefinitions.Max(f => f.Start + f.Length);
+
+            if (x.Length < minLength)
+            {
+                // 濡傛灉瀛楃涓查暱搴︿笉瓒筹紝鍙互閫夋嫨璁板綍璀﹀憡鎴栨棩蹇�
+                // 杩欓噷鎴戜滑缁х画澶勭悊锛屽敖鍙兘澶氬湴瑙f瀽瀛楁
+            }
+
+            // 杈呭姪鏂规硶锛氬畨鍏ㄧ殑瀛愬瓧绗︿覆鎴彇锛岄暱搴︿笉瓒虫椂杩斿洖绌哄瓧绗︿覆
+            string SafeSubstringOrDefault(string source, int start, int length, string fieldName)
+            {
+                if (start < 0 || start >= source.Length)
+                {
+                    return ""; // 杩斿洖绌哄瓧绗︿覆
+                }
+
+                if (length < 0)
+                {
+                    return ""; // 杩斿洖绌哄瓧绗︿覆
+                }
+
+                if (start + length > source.Length)
+                {
+                    length = source.Length - start; // 璋冩暣闀垮害浠ラ伩鍏嶈秺鐣�
+                }
+
+                return source.Substring(start, length);
+            }
+
+            // 鏋勫缓缁撴灉瀵硅薄
+            var result = new ParseMessage();
+
+            // 璁剧疆鍩烘湰瀛楁
+            result.bDir = SafeSubstringOrDefault(x, fieldDefinitions[0].Start, fieldDefinitions[0].Length, fieldDefinitions[0].Name);
+            result.bObjID = SafeSubstringOrDefault(x, fieldDefinitions[1].Start, fieldDefinitions[1].Length, fieldDefinitions[1].Name);
+            result.bReply = SafeSubstringOrDefault(x, fieldDefinitions[2].Start, fieldDefinitions[2].Length, fieldDefinitions[2].Name);
+            result.bCmdID = SafeSubstringOrDefault(x, fieldDefinitions[3].Start, fieldDefinitions[3].Length, fieldDefinitions[3].Name);
+            result.nSeqNo = SafeSubstringOrDefault(x, fieldDefinitions[4].Start, fieldDefinitions[4].Length, fieldDefinitions[4].Name);
+
+            // 璁剧疆body瀛楁
+            result.body = new ReceiveBody
+            {
+                ret = SafeSubstringOrDefault(x, fieldDefinitions[5].Start, fieldDefinitions[5].Length, fieldDefinitions[5].Name),
+                JobOrderID = SafeSubstringOrDefault(x, fieldDefinitions[6].Start, fieldDefinitions[6].Length, fieldDefinitions[6].Name),
+                priority = SafeSubstringOrDefault(x, fieldDefinitions[7].Start, fieldDefinitions[7].Length, fieldDefinitions[7].Name),
+                FromLocation = SafeSubstringOrDefault(x, fieldDefinitions[8].Start, fieldDefinitions[8].Length, fieldDefinitions[8].Name),
+                ToLocation = SafeSubstringOrDefault(x, fieldDefinitions[9].Start, fieldDefinitions[9].Length, fieldDefinitions[9].Name),
+                JobType = SafeSubstringOrDefault(x, fieldDefinitions[10].Start, fieldDefinitions[10].Length, fieldDefinitions[10].Name),
+                TrayCnt = SafeSubstringOrDefault(x, fieldDefinitions[11].Start, fieldDefinitions[11].Length, fieldDefinitions[11].Name),
+                TrayIdList = SafeSubstringOrDefault(x, fieldDefinitions[12].Start, fieldDefinitions[12].Length, fieldDefinitions[12].Name)
+            };
+
+            return result;
         }
+        
         public AGVStatusRespone GetAGVStatus()
         {
             string urlnew = url + "/ilns/AGV/getState";
@@ -1378,9 +1789,73 @@
         public StationStatus GetStationStatus(string stationName)
         {
             string urlnew = url + "/ilns/ctrl/getState";
-            var result = HttpsClient.PostAsync(urlnew, JsonConvert.DeserializeObject<Dictionary<string, object>>(new { ctrlName = "B001" }.ToJson())).Result;
+            var result = HttpsClient.PostAsync(urlnew, JsonConvert.DeserializeObject<Dictionary<string, object>>(new { ctrlName = stationName }.ToJson())).Result;
             return JsonConvert.DeserializeObject<StationStatus>(result.ToString());
         }
+        public void ReportStationErrorMeaage(string StationName)
+        {
+            string urlnew = url + "/ilns/setctrlerr";
+            var result = HttpsClient.PostAsync(urlnew, JsonConvert.DeserializeObject<Dictionary<string, object>>(new { ctrlName = StationName }.ToJson())).Result;
+        }
+        public void ReportAgvErrorMeaage(string ErrorCode)
+        {
+            string urlnew = url + "/ilns/rpterr";
+            var result = HttpsClient.PostAsync(urlnew, JsonConvert.DeserializeObject<Dictionary<string, object>>(new { code = ErrorCode }.ToJson())).Result;
+        }
+        public void AddErrorMessage(string Code, string ReportName, string Location = "")
+        {
+            var errorDescription = SqlSugarHelper.DbWMS.Queryable<Dt_ErrorDescription>().Where(x => x.ErrorCode == Code).First();
+            if (errorDescription != null)
+            {
+                Dt_HostErrorMessage hostErrorMessage = new Dt_HostErrorMessage()
+                {
+                    ErrorCode = Code,
+                    ErrorMessage = errorDescription.ErrorMessgae,
+                    AlarmSource = errorDescription.AlarmSource,
+                    Grade = errorDescription.Grade,
+                    ReportName = ReportName,
+                    Creater = "System",
+                    Location = Location == "" ? "" : Location,
+                    CreateDate = DateTime.Now,
+                };
+                SqlSugarHelper.DbWMS.Insertable(hostErrorMessage).ExecuteCommand();
+                if (Location == "")
+                {
+                    ReportAgvErrorMeaage(Code);
+                }
+                else
+                {
+                    ReportStationErrorMeaage(Location);
+                }
+
+            }
+            else
+            {
+                //tode涓嶅瓨鍦ㄥ紓甯窩ode
+            }
+        }
+        public void DeleteHostLog(int CommandID)
+        {
+            var hostLog = SqlSugarHelper.DbWMS.Queryable<Dt_HostLog>().Where(x => x.CommandID == CommandID).First();
+            if (hostLog != null)
+            {
+                SqlSugarHelper.DbWMS.Deleteable(hostLog).ExecuteCommand();
+            }
+        }
+
+        public string StationParse(string station)
+        {
+            var Station = SqlSugarHelper.DbWMS.Queryable<Dt_StationManager>().Where(x => x.HostName == station.Substring(4, 2)).First();
+            if(Station != null)
+            {
+                return Station.stationName;
+            }
+            else
+            {
+                return "";
+            }
+        }
+
         public string CapitalizeFirstLetter(string s)
         {
             if (string.IsNullOrEmpty(s))
@@ -1390,6 +1865,31 @@
             char firstChar = s[0];
             return char.ToUpper(firstChar).ToString();
         }
+
+        public string GetAGVStatus(string Status)
+        {
+            switch (Status)
+            {
+                case "Run":
+                    return "R";
+                case "Idle":
+                    return "I";
+                case "Trouble":
+                    //鏁呴殰
+                    return "T";
+                case "Pause":
+                    return "S";
+                case "Charge":
+                    return "C";
+                case "PowerOn":
+                    return "P";
+                case "PowerOFF":
+                    return "O";
+                default: break;
+            }
+            return "T";
+        }
+
         public string InsertHyphenEveryTwoChars(string input)
         {
             if (string.IsNullOrEmpty(input))
@@ -1415,5 +1915,25 @@
         }
 
         #endregion
+
+        #region 淇敼鏈湴璁$畻鏈烘椂闂�
+        // 瀹氫箟 System 缁撴瀯浣�
+        [StructLayout(LayoutKind.Sequential)]
+        public struct SYSTEMTIME
+        {
+            public ushort Year;
+            public ushort Month;
+            public ushort DayOfWeek;
+            public ushort Day;
+            public ushort Hour;
+            public ushort Minute;
+            public ushort Second;
+            public ushort Milliseconds;
+        }
+
+        // 瀵煎叆 SetLocalTime 鍑芥暟
+        [DllImport("kernel32.dll", SetLastError = true)]
+        public static extern bool SetLocalTime(ref SYSTEMTIME st);
+        #endregion
     }
 }
\ No newline at end of file

--
Gitblit v1.9.3