zhangchengsong
12 小时以前 f59f3b24814387573b5bca9a9b6c832a3720ee7e
ÏîÄ¿´úÂë/WIDESEAWCS_Server/WIDESEAWCS_Tasks/StackerCraneJob/CommonStackerCraneJob.cs
@@ -1,22 +1,29 @@
using Autofac.Core;
using HslCommunication;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Quartz;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Eventing.Reader;
using System.DirectoryServices.Protocols;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using WIDESEA_Comm.Http;
using WIDESEA_Common.Log;
using WIDESEAWCS_Common.TaskEnum;
using WIDESEAWCS_Core;
using WIDESEAWCS_Core.Enums;
using WIDESEAWCS_DTO.TaskInfo;
using WIDESEAWCS_ISystemServices;
using WIDESEAWCS_ITaskInfoRepository;
using WIDESEAWCS_ITaskInfoService;
@@ -28,7 +35,9 @@
using WIDESEAWCS_QuartzJob.Models;
using WIDESEAWCS_QuartzJob.Service;
using WIDESEAWCS_QuartzJob.StackerCrane.Enum;
using WIDESEAWCS_TaskInfoService;
using WIDESEAWCS_Tasks.StackerCraneJob;
using static WIDESEAWCS_Model.Models.System.JobError;
namespace WIDESEAWCS_Tasks
{
@@ -47,8 +56,11 @@
            _taskExecuteDetailService = taskExecuteDetailService;
            _taskRepository = taskRepository;
            _routerService = routerService;
            _DtPlatformStationService= dt_PlatformStationService;
            _DtPlatformStationService = dt_PlatformStationService;
        }
        private static readonly Dictionary<string, bool> _deviceLastStatus = new Dictionary<string, bool>();
        public string urlWMSdeverror = WIDESEAWCS_Core.Helper.AppSettings.Configuration["urlWMSdeverror"];
        public Task Execute(IJobExecutionContext context)
        {
@@ -57,6 +69,39 @@
                CommonStackerCrane commonStackerCrane = (CommonStackerCrane)context.JobDetail.JobDataMap.Get("JobParams");
                if (commonStackerCrane != null)
                {
                WriteLog.Write_Log("堆垛机当前状态信息", $"{commonStackerCrane.DeviceCode}库堆垛机当前状态",
                                                $"堆垛机设备状态地址:【DB105.2.0】,读取的数据:【{commonStackerCrane.StackerCraneAutoStatusDes}】\n" +
                                               $"堆垛机工作模式地址:【DB105.3.0】,读取的数据:【{commonStackerCrane.StackerCraneStatusDes}】\n" +
                                               $"堆垛机作业状态地址:【DB105.22.0】,读取的数据:【{commonStackerCrane.StackerCraneWorkStatusDes}】\n" +
                                               $"堆垛机当前任务执行中地址:【DB105.18.0】,读取的数据:【{commonStackerCrane.CurrentTaskNum}】\n");
                    // èŽ·å–å½“å‰çŠ¶æ€
                    bool isFaultNow = commonStackerCrane.StackerCraneStatusDes.Equals("故障");
                    string deviceCode = commonStackerCrane.DeviceCode;
                    if (!_deviceLastStatus.ContainsKey(deviceCode))
                    {
                        _deviceLastStatus[deviceCode] = isFaultNow;
                        if (isFaultNow)
                        {
                            SendDevError(commonStackerCrane, "66", "start", ReadStackerFaults(commonStackerCrane));
                        }
                    }
                    else
                    {
                        bool lastStatus = _deviceLastStatus[deviceCode];
                        if (!lastStatus && isFaultNow)
                        {
                            SendDevError(commonStackerCrane, "66", "start", ReadStackerFaults(commonStackerCrane));
                            _deviceLastStatus[deviceCode] = true;
                        }
                        else if (lastStatus && !isFaultNow)
                        {
                            SendDevError(commonStackerCrane, "99", "stop", "堆垛机恢复正常");
                            _deviceLastStatus[deviceCode] = false;
                        }
                    }
                    UpdateHandShake(commonStackerCrane.CurrentTaskNum, commonStackerCrane.StackerCraneWorkStatusDes);
                    //任务完成StackerCraneWorkStatus
                    if (commonStackerCrane.StackerCraneWorkStatusValue == StackerCraneWorkStatus.WorkCompleted)
                    {
@@ -64,23 +109,22 @@
                        Dt_Task? currtask = _taskService.CurrtaskInfo(commonStackerCrane.CurrentTaskNum);
                        if(currtask != null)
                        {
                            string PalletCode = "";
                            //判断任务类型
                            if(currtask.TaskType==  (int)TaskTypeEnum.Inventorybound)
                            if (currtask.TaskType==  (int)TaskTypeEnum.Inventorybound)
                            {
                                //读取条码,进行配对
                                DeviceProDTO? deviceProDTO = commonStackerCrane.DeviceProDTOs.FirstOrDefault(x => x.DeviceProParamName == "SCBarcode");
                                byte[] bytes = commonStackerCrane.Communicator.Read(deviceProDTO.DeviceProAddress, 64);
                                string result = Encoding.ASCII.GetString(bytes).Replace(" ", "");
                                bool pandianBort = false;
                                if(currtask.PalletCode== result) pandianBort= true;
                                //读取的托盘条码
                                PalletCode = Encoding.ASCII.GetString(bytes).Replace(" ", "");
                            }
                            WebResponseContent webResponse = _taskService.StackCraneTaskCompleted(commonStackerCrane.CurrentTaskNum);
                            WebResponseContent webResponse = _taskService.StackCraneTaskCompleted(commonStackerCrane.CurrentTaskNum, PalletCode);
                            if (webResponse.Status)
                            {
                                Task.Run(() => WriteLog.Write_Log("堆垛机任务上报完成信息", "堆垛机任务上报完成信息", $"【{commonStackerCrane.DeviceCode}】库堆垛机上报任务号:【{commonStackerCrane.CurrentTaskNum}】完成信号!"));
                                bool ddjfk = commonStackerCrane.SetValue(StackerCraneDBName.WorkType, 5);
                            }
@@ -90,9 +134,11 @@
                    if (commonStackerCrane.StackerCraneAutoStatusValue == StackerCraneAutoStatus.Automatic && commonStackerCrane.StackerCraneStatusValue == StackerCraneStatus.Normal)
                    {
                        if (commonStackerCrane.StackerCraneWorkStatusValue == StackerCraneWorkStatus.Standby)
                        {
                            Console.WriteLine("进行获取任务");
                            Dt_Task? task = GetTask(commonStackerCrane);
                            if (task != null)
                            {
@@ -115,28 +161,50 @@
            catch (Exception ex)
            {
                Console.WriteLine(nameof(CommonStackerCraneJob) + ":" + ex.ToString());
                WriteLog.Write_Log("堆垛机报错信息", "堆垛机报错信息", $"堆垛机报错信息:【{ex.ToString()}】");
            }
            return Task.CompletedTask;
        }
        /// <summary>
        /// ä»»åŠ¡å®Œæˆäº‹ä»¶è®¢é˜…çš„æ–¹æ³•
        /// æ•…障上报(改为await调用,修复异步BUG)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommonStackerCrane_StackerCraneTaskCompletedEventHandler(object? sender, WIDESEAWCS_QuartzJob.StackerCrane.StackerCraneTaskCompletedEventArgs e)
        public void SendDevError(CommonStackerCrane crane, string errorcode, string dealType, string errorInfo = "")
        {
            CommonStackerCrane? commonStackerCrane = sender as CommonStackerCrane;
            if (commonStackerCrane != null)
            CommandResult commandResult = new CommandResult();
            try
            {
                if (commonStackerCrane.GetValue<StackerCraneDBName, short>(StackerCraneDBName.WorkType) != 5 && e.TaskNum !=0)
                DeviceErrorRequest deviceErrorRequest = new DeviceErrorRequest
                {
                    //Console.Out.WriteLine("TaskCompleted" + e.TaskNum);
                    _taskService.StackCraneTaskCompleted(e.TaskNum);
                    commonStackerCrane.SetValue(StackerCraneDBName.WorkType, 5);
                }
                    devErrorJsons = new List<DeviceErrorInfo>
                    {
                        new DeviceErrorInfo
                        {
                            devuuid = crane.DeviceCode,
                            id = "",
                            errorcode = errorcode,
                            errorinfo = errorInfo,
                            erroraddress = "DB107",
                            warehouse = crane.DeviceCode == "B" ? "ZR17":(crane.DeviceCode == "G"?"ZR18":"ZR16"),
                            remark = dealType == "start" ? "设备异常" : "设备恢复",
                            devname =  $"{crane.DeviceCode}库堆垛机",
                        }
                    },
                    dealType = dealType,
                    psd = "akjfapjfpadaoif",
                };
                commandResult = HttpHelper.Post<CommandResult>(urlWMSdeverror, deviceErrorRequest, "设备故障回调");
                WriteLog.Write_Log("同步给上游设备故障信息", "设备故障信息", $"设备id:【{crane.DeviceCode}】,成功", $"设备回调状态:【{dealType}】,异常信息:【{errorInfo}】\n" +
                    $"调用上游返回结果信息:【{commandResult?.ToJsonString() ?? "返回结果为null"}】");
            }
            catch (Exception ex)
            {
                WriteLog.Write_Log("故障上报失败", "错误", ex.ToString());
            }
        }
        /// <summary>
        /// èŽ·å–ä»»åŠ¡
@@ -163,8 +231,9 @@
                                return taskItem;
                            }
                        }
                        else if (taskItem.TaskType == (int)TaskTypeEnum.Inbound || taskItem.TaskType == (int)TaskTypeEnum.Inventorybound)
                        else if ((InTaskStationIsOccupied(taskItem.SourceAddress, taskItem.Roadway) && taskItem.TaskType == (int)TaskTypeEnum.Inbound) || taskItem.TaskType == (int)TaskTypeEnum.Inventorybound)
                        {
                            return taskItem;
                        }
                    }
@@ -188,47 +257,62 @@
        {
            try
            {
                if (Roadway == "C")
                CommonConveyorLine? conveyorLine = null;
                lock (Storage.Devices)
                {
                    IDevice? device = Storage.Devices.FirstOrDefault(x => x.DeviceCode == "1004");
                    if (device == null) return false;
                    CommonConveyorLine conveyorLine = (CommonConveyorLine)device;
                    DeviceProDTO? deviceProDTO = conveyorLine.DeviceProDTOs.FirstOrDefault(x => x.DeviceChildCode == NextAddress && x.DeviceProParamName == "StationNum");
                    DeviceProDTO? HandShakeprodto = conveyorLine.DeviceProDTOs.FirstOrDefault(x => x.DeviceChildCode == NextAddress && x.DeviceProParamName == "HandShake");
                    if (deviceProDTO == null || HandShakeprodto == null) return false;
                    int StationNum = conveyorLine.Communicator.Read<ushort>(deviceProDTO.DeviceProAddress);
                    int HandShake = conveyorLine.Communicator.Read<ushort>(HandShakeprodto.DeviceProAddress);
                    if (StationNum == 0 && HandShake == 0 && Roadway == "C")
                    {
                        return true;
                    }
                    string deviceCode = Roadway == "C" ? "1004" : "1003";
                    conveyorLine = Storage.Devices.FirstOrDefault(x => x.DeviceCode == deviceCode) as CommonConveyorLine;
                }
                else
                {
                    IDevice? device = Storage.Devices.FirstOrDefault(x => x.DeviceCode == "1003");
                    if (device == null) return false;
                    CommonConveyorLine conveyorLine = (CommonConveyorLine)device;
                    DeviceProDTO? deviceProDTO = conveyorLine.DeviceProDTOs.FirstOrDefault(x => x.DeviceChildCode == NextAddress && x.DeviceProParamName == "StationNum");
                    DeviceProDTO? HandShakeprodto = conveyorLine.DeviceProDTOs.FirstOrDefault(x => x.DeviceChildCode == NextAddress && x.DeviceProParamName == "HandShake");
                    if (deviceProDTO == null || HandShakeprodto == null) return false;
                if (conveyorLine == null) return false;
                    int StationNum = conveyorLine.Communicator.Read<ushort>(deviceProDTO.DeviceProAddress);
                    int HandShake = conveyorLine.Communicator.Read<ushort>(HandShakeprodto.DeviceProAddress);
                    if ((StationNum == 1 && HandShake == 0 && Roadway == "B") || (StationNum == 0 && HandShake == 0 && Roadway != "B"))
                    {
                        return true;
                    }
                }
                DeviceProDTO? deviceProDTO = conveyorLine.DeviceProDTOs.FirstOrDefault(x => x.DeviceChildCode == NextAddress && x.DeviceProParamName == "StationNum");
                DeviceProDTO? HandShakeprodto = conveyorLine.DeviceProDTOs.FirstOrDefault(x => x.DeviceChildCode == NextAddress && x.DeviceProParamName == "HandShake");
                if (deviceProDTO == null || HandShakeprodto == null) return false;
                int StationNum = conveyorLine.Communicator.Read<ushort>(deviceProDTO.DeviceProAddress);
                int HandShake = conveyorLine.Communicator.Read<ushort>(HandShakeprodto.DeviceProAddress);
                WriteLog.Write_Log("出库库口状态信息", "出库库口状态信息", $"库口是【{NextAddress}】,申请状态地址:【{HandShakeprodto.DeviceProAddress}】,读取的数据:【{HandShake}】\n库口是否有货状态地址:【{deviceProDTO.DeviceProAddress}】,读取的数据【{StationNum}】");
                  if (Roadway == "C" || Roadway == "G") return StationNum == 0 && HandShake == 0;
                return (StationNum == 1 && HandShake == 0 && Roadway == "B");
            }
            catch (Exception ex)
            {
                Console.WriteLine("读取站台信息错误:"+ex.Message);
              Console.WriteLine("读取站台信息错误:" + ex.Message);
                return false;
            }
            return false;
        }
        /// <summary>
        /// å…¥åº“任务库口有货无货状态
        /// </summary>
        public bool InTaskStationIsOccupied(string SourceAddress, string Roadway)
        {
            try
            {
                CommonConveyorLine? conveyorLine = null;
                lock (Storage.Devices)
                {
                    string deviceCode = Roadway == "C" ? "1004" : "1003";
                    conveyorLine = Storage.Devices.FirstOrDefault(x => x.DeviceCode == deviceCode) as CommonConveyorLine;
                }
                if (conveyorLine == null) return false;
                DeviceProDTO? deviceProDTO = conveyorLine.DeviceProDTOs.FirstOrDefault(x => x.DeviceChildCode == SourceAddress && x.DeviceProParamName == "StationNum");
                DeviceProDTO? HandShakeprodto = conveyorLine.DeviceProDTOs.FirstOrDefault(x => x.DeviceChildCode == SourceAddress && x.DeviceProParamName == "HandShake");
                if (deviceProDTO == null || HandShakeprodto == null) return false;
                int StationNum = conveyorLine.Communicator.Read<ushort>(deviceProDTO.DeviceProAddress);
                int HandShake = conveyorLine.Communicator.Read<ushort>(HandShakeprodto.DeviceProAddress);
                WriteLog.Write_Log("入库库口状态信息", "入库库口状态信息", $"库口是【{SourceAddress}】,申请状态地址:【{HandShakeprodto.DeviceProAddress}】,读取的数据:【{HandShake}】\n库口是否有货状态地址:【{deviceProDTO.DeviceProAddress}】,读取的数据【{StationNum}】");
                return (StationNum == 1 && HandShake == 0) ? true : false;
            }
            catch (Exception ex)
            {
               Console.WriteLine("读取站台信息错误:" + ex.Message);
                return false;
            }
        }
        /// <summary>
        /// ä»»åŠ¡å®žä½“è½¬æ¢æˆå‘½ä»¤Model
@@ -240,16 +324,34 @@
        {
            StackerCraneTaskCommand stackerCraneTaskCommand = new StackerCraneTaskCommand();
            stackerCraneTaskCommand.Barcode = task.PalletCode;
            stackerCraneTaskCommand.TaskNum = task.TaskNum;
            stackerCraneTaskCommand.WorkType = 1;
            stackerCraneTaskCommand.TrayType = 0;
            if (task.Roadway == "B" || task.Roadway == "C")
            {
                //判断 task.PalletCode æ˜¯ä¸æ˜¯ä¸€ä¸ªæœ‰æ•ˆçš„ GUID
                stackerCraneTaskCommand.Barcode = stackerCraneTaskCommand.Barcode = Guid.TryParse(task.PalletCode, out var guid) ? guid.ToString("N")[0..6] : task.PalletCode;
            }
            else if (task.Roadway == "G" )
            {
                if (Guid.TryParse(task.PalletCode, out var palletGuid))
                {
                    stackerCraneTaskCommand.Barcode = palletGuid.ToString("N")[0..6];
                    // æ ‡å‡†GUID就是36位,所以直接判断长度即可
                    stackerCraneTaskCommand.TrayType = (short)(task.PalletCode.Length == 36 ? 1 : 2);
                }
                else
                {
                    stackerCraneTaskCommand.Barcode = task.PalletCode;
                    stackerCraneTaskCommand.TrayType = 2;
                }
            }
            if (task.TaskType == (int)TaskTypeEnum.Inbound)//判断是否是入库任务
            {
                //获取站台编号
                Dt_PlatformStation dt_Platform=_DtPlatformStationService.getStatiomInfo(task.SourceAddress);
                Dt_PlatformStation dt_Platform = _DtPlatformStationService.getStatiomInfo(task.SourceAddress);
                string[] targetCodest = dt_Platform.Station_storey.Split("-");
                if (targetCodest.Length == 3)
                {
@@ -270,7 +372,7 @@
                    string EndRow = EndCodest[0].Substring(1);
                    string SCEndRow = LaneModification(task.Roadway, int.Parse(EndRow));
                    stackerCraneTaskCommand.EndRow = Convert.ToInt16(SCEndRow );
                    stackerCraneTaskCommand.EndRow = Convert.ToInt16(SCEndRow);
                    stackerCraneTaskCommand.EndColumn = Convert.ToInt16(EndCodest[1]);
                    stackerCraneTaskCommand.EndLayer = Convert.ToInt16(EndCodest[2]);
                }
@@ -328,7 +430,7 @@
                if (EndCodest.Length == 3)
                {
                    string EndRow = EndCodest[0].Substring(1);
                   string SCEnRow=LaneModification(task.Roadway,int.Parse(EndRow));
                    string SCEnRow = LaneModification(task.Roadway, int.Parse(EndRow));
                    stackerCraneTaskCommand.EndRow = Convert.ToInt16(SCEnRow);
                    stackerCraneTaskCommand.EndColumn = (short)(Convert.ToInt16(EndCodest[1]) + 1);
@@ -336,13 +438,13 @@
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"移库任务起点错误,起点:【{task.CurrentAddress}】");
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"盘点任务起点错误,起点:【{task.CurrentAddress}】");
                    return null;
                }
            }
            return stackerCraneTaskCommand;
        }
@@ -361,5 +463,69 @@
                return SCRow.ToString();
            }
        }
        /// <summary>
        /// ç›‘测G库、C库出库放货时屏蔽光栅
        /// </summary>
        /// <param name="taskNum"></param>
        /// <param name="stackerCraneWorkStatusDes"></param>
        public void UpdateHandShake(int taskNum, string stackerCraneWorkStatusDes)
        {
                try
                {
                    var dtTask = _taskRepository.QueryFirst(x => x.TaskNum == taskNum);
                    if (dtTask == null) return;
                    string[] targets = { "G02", "G03", "G04", "C02", "C01" };
                    if (dtTask.TaskType != 100 || !targets.Contains(dtTask.TargetAddress)) return;
                    short writeValue = stackerCraneWorkStatusDes switch
                    {
                        "放货中" => 1,
                        "任务完成" => 0,
                        _ => -1
                    };
                    if (writeValue == -1) return;
                    CommonConveyorLine? conveyorLine = null;
                    lock (Storage.Devices)
                    {
                        string deviceCode = dtTask.CurrentAddress.StartsWith("C") ? "1004" : "1003";
                        conveyorLine = Storage.Devices.FirstOrDefault(x => x.DeviceCode == deviceCode) as CommonConveyorLine;
                    }
                    if (conveyorLine == null) return;
                    var handShake = conveyorLine.DeviceProDTOs.FirstOrDefault(x => x.DeviceChildCode == dtTask.TargetAddress && x.DeviceProParamName == "HandShake");
                    if (handShake == null) return;
                    conveyorLine.Communicator.Write<short>(handShake.DeviceProAddress, writeValue);
                }
                catch
                { }
        }
        /// <summary>
        /// è¯»å–故障(优化GC)
        /// </summary>
        public string ReadStackerFaults(CommonStackerCrane crane)
        {
            try
            {
                foreach (StackerFault fault in Enum.GetValues(typeof(StackerFault)))
                {
                    try
                    {
                        bool isFault = crane.Communicator.Read<bool>(fault.ToPlcAddress());
                        if (isFault)
                            return fault.GetDesc();
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
                WriteLog.Write_Log("DB107故障读取异常", "错误", ex.ToString());
            }
            return string.Empty;
        }
    }
}