huangxiaoqiang
2025-08-27 5a8b16b77cbbbe8137603ba9381f81f95f58135f
ÏîÄ¿´úÂë/WCS/WCSServices/WIDESEAWCS_Tasks/Ô­ÁÏ¿â/StackerCraneJob_YLSC3.cs
@@ -1,12 +1,436 @@
using System;
using Microsoft.AspNetCore.Components.Routing;
using Quartz;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEAWCS_Common.TaskEnum;
using WIDESEAWCS_Core.Enums;
using WIDESEAWCS_IBasicInfoRepository;
using WIDESEAWCS_ITaskInfoRepository;
using WIDESEAWCS_ITaskInfoService;
using WIDESEAWCS_Model.Models;
using WIDESEAWCS_QuartzJob;
using WIDESEAWCS_QuartzJob.DeviceBase;
using WIDESEAWCS_QuartzJob.Models;
using WIDESEAWCS_QuartzJob.Service;
using WIDESEAWCS_QuartzJob.StackerCrane.Enum;
using WIDESEAWCS_Tasks.StackerCraneJob;
using WIDESEAWCS_Tasks;
using WIDESEAWCS_Core;
using SqlSugar.Extensions;
using WIDESEAWCS_Tasks.ConveyorLineJob;
using WIDESEAWCS_QuartzJob.Repository;
namespace WIDESEAWCS_Tasks.原料库
namespace WIDESEAWCS_Tasks
{
    internal class StackerCraneJob_YLSC3
    [DisallowConcurrentExecution]
    public class StackerCraneJob_YLSC3 : JobBase, IJob
    {
        private readonly ITaskService _taskService;
        private readonly ITaskExecuteDetailService _taskExecuteDetailService;
        private readonly ITaskRepository _taskRepository;
        private readonly IRouterService _routerService;
        private readonly IRouterRepository _routerRepository;
        private readonly IStationMangerRepository _stationMangerRepository;
        public StackerCraneJob_YLSC3(ITaskService taskService, ITaskExecuteDetailService taskExecuteDetailService, ITaskRepository taskRepository, IRouterService routerService, IStationMangerRepository stationMangerRepository, IRouterRepository routerRepository)
        {
            _taskService = taskService;
            _taskExecuteDetailService = taskExecuteDetailService;
            _taskRepository = taskRepository;
            _routerService = routerService;
            _stationMangerRepository = stationMangerRepository;
            _routerRepository = routerRepository;
        }
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                CommonStackerCrane commonStackerCrane = (CommonStackerCrane)context.JobDetail.JobDataMap.Get("JobParams");
                if (commonStackerCrane != null)
                {
                    if (!commonStackerCrane.IsEventSubscribed)
                    {
                        commonStackerCrane.StackerCraneTaskCompletedEventHandler += CommonStackerCrane_StackerCraneTaskCompletedEventHandler;//订阅任务完成事件
                    }
                    commonStackerCrane.CheckStackerCraneTaskCompleted();//防止任务完成事件监测超时,再手动触发一次
                    if (commonStackerCrane.StackerCraneAutoStatusValue == StackerCraneAutoStatus.Automatic && commonStackerCrane.StackerCraneStatusValue == StackerCraneStatus.Normal && commonStackerCrane.StackerCraneWorkStatusValue == StackerCraneWorkStatus.Standby)
                    {
                        short stackerError = commonStackerCrane.Communicator.Read<short>("DB1000.54.0");
                        if (stackerError == 0)
                        {
                            Dt_Task? task = GetTask(commonStackerCrane);
                            if (task != null)
                            {
                                YLStackerCraneTaskCommand? stackerCraneTaskCommand = ConvertToStackerCraneTaskCommand(task);
                                if (stackerCraneTaskCommand != null)
                                {
                                    bool sendFlag = commonStackerCrane.SendCommand(stackerCraneTaskCommand);
                                    if (sendFlag)
                                    {
                                        commonStackerCrane.LastTaskType = task.TaskType;
                                        task.Dispatchertime = DateTime.Now;
                                        task.ExceptionMessage = "";
                                        //_taskService.UpdateTask(task, TaskStatusEnum.SC_Executing);
                                        _taskService.UpdateTaskStatusToNext(task);
                                        commonStackerCrane.Communicator.Write("DB1000.20.0", true);
                                        //延时1s
                                        Thread.Sleep(1000);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteError(nameof(StackerCraneJob_CP), ex.Message, ex);
            }
            return Task.CompletedTask;
        }
        /// <summary>
        /// ä»»åŠ¡å®Œæˆäº‹ä»¶è®¢é˜…çš„æ–¹æ³•
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommonStackerCrane_StackerCraneTaskCompletedEventHandler(object? sender, WIDESEAWCS_QuartzJob.StackerCrane.StackerCraneTaskCompletedEventArgs e)
        {
            CommonStackerCrane? commonStackerCrane = sender as CommonStackerCrane;
            if (commonStackerCrane != null)
            {
                if (!commonStackerCrane.GetValue<StackerCraneDBName, bool>(StackerCraneDBName.WriteFinish))
                {
                    if (StackerCraneTaskCompleted(e.TaskNum, commonStackerCrane.DeviceCode).Status)
                    {
                        commonStackerCrane.SetValue(StackerCraneDBName.WriteFinish, true);
                    }
                }
            }
        }
        public WebResponseContent StackerCraneTaskCompleted(int taskNum, string deviceCode)
        {
            try
            {
                Dt_Task task = _taskRepository.QueryFirst(x => x.TaskNum == taskNum && x.TaskState == TaskStatusEnum.SC_Executing.ObjToInt());
                if (task != null)
                {
                    if (task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.OutbondGroup)
                    {
                        Dt_StationManger stationManger = _stationMangerRepository.QueryFirst(x => x.StackerCraneStationCode == task.NextAddress && x.StackerCraneCode == deviceCode);
                        if (stationManger == null)
                        {
                            _taskExecuteDetailService.AddTaskExecuteDetail(taskNum, $"输送线出库站点未配置,{task.NextAddress}");
                            _taskService.UpdateTaskExceptionMessage(taskNum, $"输送线出库站点未配置,{task.NextAddress}");
                            return WebResponseContent.Instance.Error($"输送线出库站点未配置,{task.NextAddress}");
                        }
                        Dt_Router router = _routerRepository.QueryFirst(x => x.InOutType == task.TaskType && x.StartPosi == stationManger.StationCode && x.ChildPosi == stationManger.StationDeviceCode);
                        if (router == null)
                        {
                            _taskService.UpdateTaskExceptionMessage(taskNum, $"未找到路由信息,{task.NextAddress}");
                            WriteError(deviceCode, $"未找到路由信息,{task.NextAddress}");
                            return WebResponseContent.Instance.Error($"未找到路由信息,{task.NextAddress}");
                        }
                        int oldStatus = task.TaskState;
                        //原料一楼出库下发线体逻辑
                        if (stationManger.StationDeviceCode == "CL1_YL")
                        {
                            IDevice? device = Storage.Devices.FirstOrDefault(x => x.DeviceCode == stationManger.StationDeviceCode);
                            if (device != null)
                            {
                                OtherDevice conveyorLine = (OtherDevice)device;
                                conveyorLine.SetValue(ConveyorLineDBName.TaskNum, taskNum, stationManger.StationCode);
                                conveyorLine.SetValue(ConveyorLineDBName.TargetAddress, router.NextPosi, stationManger.StationCode);
                                conveyorLine.SetValue(ConveyorLineDBName.ResponState, 86, stationManger.StationCode);
                                // å †åž›æœºå®Œæˆ
                                _taskService.UpdateTask(task, TaskStatusEnum.Line_Execute, deviceCode: stationManger.StationDeviceCode, currentAddress: stationManger.StationCode, nextAddress: router.NextPosi);
                            }
                            else
                            {
                                WriteInfo(deviceCode, $"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法发送输送线出库信号");
                                _taskService.UpdateTaskExceptionMessage(taskNum, $"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法发送输送线出库信号");
                                return WebResponseContent.Instance.Error($"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法发送输送线出库信号");
                            }
                        }//原料二楼出库下发线体逻辑
                        else
                        {
                            IDevice? device = Storage.Devices.FirstOrDefault(x => x.DeviceCode == stationManger.StationDeviceCode);
                            if (device != null)
                            {
                                CommonConveyorLine conveyorLine = (CommonConveyorLine)device;
                                conveyorLine.SetValue(WR_CLineYLDB.WR_Task, taskNum, stationManger.StationCode);
                                conveyorLine.SetValue(WR_CLineYLDB.WR_ToHode, router.NextPosi, stationManger.StationCode);
                                conveyorLine.SetValue(WR_CLineYLDB.WR_Reresult, 86, stationManger.StationCode);
                                _taskService.UpdateTaskStatusToNext(task);
                            }
                            else
                            {
                                WriteInfo(deviceCode, $"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法发送输送线出库信号");
                                _taskService.UpdateTaskExceptionMessage(taskNum, $"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法发送输送线出库信号");
                                return WebResponseContent.Instance.Error($"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法发送输送线出库信号");
                            }
                        }
                        _taskExecuteDetailService.AddTaskExecuteDetail(taskNum, $"系统自动流程,任务状态从【{oldStatus}】转到【{task.TaskState}】");
                        WriteInfo(deviceCode, $"堆垛机出库任务完成,任务号:{taskNum}");
                    }
                    else if (task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.InboundGroup || task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.RelocationGroup)
                    {
                        WriteInfo(deviceCode, $"堆垛机任务完成,任务号:{taskNum}");
                        _taskService.TaskCompleted(taskNum);
                    }
                    else
                    {
                        WriteInfo(deviceCode, $"未找到该任务类型回调WMS任务完成接口,{task.TaskType}");
                        _taskExecuteDetailService.AddTaskExecuteDetail(taskNum, $"未找到该任务类型回调WMS任务完成接口,{task.TaskType}");
                        _taskService.UpdateTaskExceptionMessage(taskNum, $"未找到该任务类型回调WMS任务完成接口,{task.TaskType}");
                    }
                }
                else
                {
                    WriteInfo(deviceCode, $"未找到任务信息,任务号:{taskNum}");
                    return WebResponseContent.Instance.Error($"未找到任务信息,任务号:{taskNum}");
                }
                return WebResponseContent.Instance.OK();
            }
            catch (Exception ex)
            {
                WriteError(deviceCode, $"任务完成错误", ex);
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
        /// <summary>
        /// èŽ·å–ä»»åŠ¡
        /// </summary>
        /// <param name="commonStackerCrane">堆垛机对象</param>
        /// <returns></returns>
        private Dt_Task? GetTask(CommonStackerCrane commonStackerCrane)
        {
            Dt_Task? task;
            if (commonStackerCrane.LastTaskType == null)
            {
                task = _taskService.QueryStackerCraneTask(commonStackerCrane.DeviceCode);
            }
            else
            {
                if (commonStackerCrane.LastTaskType.GetValueOrDefault().GetTaskTypeGroup() == TaskTypeGroup.OutbondGroup)
                {
                    //上一个为出库则查是否存在入库任务 äº¤æ›¿æ‰§è¡Œ
                    task = _taskService.QueryStackerCraneInTask(commonStackerCrane.DeviceCode);
                    if (task == null)
                    {
                        task = _taskService.QueryStackerCraneOutTask(commonStackerCrane.DeviceCode);
                    }
                }
                else
                {
                    //上一个为入库则查是否存在出库任务 äº¤æ›¿æ‰§è¡Œ
                    task = _taskService.QueryStackerCraneOutTask(commonStackerCrane.DeviceCode);
                    if (task == null)
                    {
                        task = _taskService.QueryStackerCraneInTask(commonStackerCrane.DeviceCode);
                    }
                }
            }
            if (task != null && task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.OutbondGroup)
            {
                //判断出库站台占用
                if (OutTaskStationIsOccupied(task) == null)
                {
                    bool flag = false;
                    List<string> otherOutStaionCodes = _routerService.QueryNextRoutes(commonStackerCrane.DeviceCode, task.NextAddress, task.TaskType).Select(x => x.ChildPosi).ToList();
                    List<Dt_Task> tasks = _taskService.QueryStackerCraneOutTasks(commonStackerCrane.DeviceCode, otherOutStaionCodes);
                    foreach (var item in tasks)
                    {
                        if (OutTaskStationIsOccupied(task) != null)
                        {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag)
                    {
                        task = _taskService.QueryStackerCraneInTask(commonStackerCrane.DeviceCode);
                    }
                }
            }
            if (task == null)
            {
                task = _taskService.QuertStackerCraneTask(commonStackerCrane.DeviceCode, TaskTypeGroup.RelocationGroup);
            }
            return task;
        }
        /// <summary>
        /// å‡ºåº“任务判断出库站台是否被占用
        /// </summary>
        /// <param name="task">任务实体</param>
        /// <returns>如果未被占用,返回传入的任务信息,否则,返回null</returns>
        private Dt_Task? OutTaskStationIsOccupied([NotNull] Dt_Task task)
        {
            Dt_StationManger? stationManger = _stationMangerRepository.QueryFirst(x => x.StationCode == task.NextAddress && x.StackerCraneCode == task.DeviceCode);
            if (stationManger != null)
            {
                if (stationManger.StationDeviceCode == "CL1_YL")
                {
                    IDevice? device = Storage.Devices.FirstOrDefault(x => x.DeviceCode == stationManger.StationDeviceCode);
                    if (device != null)
                    {
                        OtherDevice client = (OtherDevice)device;
                        if (client.GetValue<WR_CLineYLDB, short>(WR_CLineYLDB.WR_Request, stationManger.StationCode) != 99)//出库站台未被占用
                        {
                            task.NextAddress = stationManger.StackerCraneStationCode;
                            _taskRepository.UpdateData(task);
                            return task;
                        }
                    }
                    else
                    {
                        WriteInfo(task.DeviceCode, $"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法判断出库站台是否被占用");
                        _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法判断出库站台是否被占用");
                    }
                }
                else
                {
                    IDevice? device = Storage.Devices.FirstOrDefault(x => x.DeviceCode == stationManger.StationDeviceCode);
                    if (device != null)
                    {
                        CommonConveyorLine client = (CommonConveyorLine)device;
                        if (client.GetValue<ConveyorLineDBName, short>(ConveyorLineDBName.InteractiveSignal, stationManger.StationCode) != 99)//出库站台未被占用
                        {
                            task.NextAddress = stationManger.StackerCraneStationCode;
                            _taskRepository.UpdateData(task);
                            return task;
                        }
                    }
                    else
                    {
                        WriteInfo(task.DeviceCode, $"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法判断出库站台是否被占用");
                        _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"未找到出库站台【{stationManger.StationDeviceCode}】对应的通讯对象,无法判断出库站台是否被占用");
                    }
                }
            }
            else
            {
                WriteInfo(task.DeviceCode, $"未找到站台【{task.NextAddress}】信息,无法校验站台");
                _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"未找到站台【{task.NextAddress}】信息,无法校验站台");
            }
            return null;
        }
        /// <summary>
        /// ä»»åŠ¡å®žä½“è½¬æ¢æˆå‘½ä»¤Model
        /// </summary>
        /// <param name="task">任务实体</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public YLStackerCraneTaskCommand? ConvertToStackerCraneTaskCommand([NotNull] Dt_Task task)
        {
            YLStackerCraneTaskCommand stackerCraneTaskCommand = new YLStackerCraneTaskCommand();
            stackerCraneTaskCommand.TaskNum = task.TaskNum;
            stackerCraneTaskCommand.WorkType = 5;
            stackerCraneTaskCommand.PalletType = Convert.ToInt16(task.PalletType);
            if (task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.InboundGroup)//判断是否是入库任务
            {
                string[] startCodes = task.CurrentAddress.Split("-");
                if (startCodes.Length == 3)
                {
                    stackerCraneTaskCommand.StartRow = Convert.ToInt16(startCodes[0]);
                    stackerCraneTaskCommand.StartColumn = Convert.ToInt16(startCodes[1]);
                    stackerCraneTaskCommand.StartLayer = Convert.ToInt16(startCodes[2]);
                }
                else
                {
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"入库任务起点错误,起点:【{task.CurrentAddress}】");
                    return null;
                }
                string[] targetCodes = task.NextAddress.Split("-");
                if (targetCodes.Length == 5)
                {
                    stackerCraneTaskCommand.EndRow = Convert.ToInt16(targetCodes[1]);
                    stackerCraneTaskCommand.EndColumn = Convert.ToInt16(targetCodes[2]);
                    stackerCraneTaskCommand.EndLayer = Convert.ToInt16(targetCodes[3]);
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"入库任务终点错误,终点:【{task.NextAddress}】");
                    return null;
                }
            }
            else if (task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.OutbondGroup)//判断是否是出库任务
            {
                string[] targetCodes = task.NextAddress.Split("-");
                if (targetCodes.Length == 3)
                {
                    stackerCraneTaskCommand.EndRow = Convert.ToInt16(targetCodes[1]);
                    stackerCraneTaskCommand.EndColumn = Convert.ToInt16(targetCodes[2]);
                    stackerCraneTaskCommand.EndLayer = Convert.ToInt16(targetCodes[3]);
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"出库任务下一地址点错误,起点:【{task.NextAddress}】");
                    return null;
                }
                string[] sourceCodes = task.CurrentAddress.Split("-");
                if (sourceCodes.Length == 5)
                {
                    stackerCraneTaskCommand.StartRow = Convert.ToInt16(sourceCodes[0]);
                    stackerCraneTaskCommand.StartColumn = Convert.ToInt16(sourceCodes[1]);
                    stackerCraneTaskCommand.StartLayer = Convert.ToInt16(sourceCodes[2]);
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"出库任务起点错误,起点:【{task.CurrentAddress}】");
                    return null;
                }
            }
            else if (task.TaskType.GetTaskTypeGroup() == TaskTypeGroup.RelocationGroup)//判断是否是移库任务
            {
                string[] targetCodes = task.NextAddress.Split("-");
                if (targetCodes.Length == 5)
                {
                    stackerCraneTaskCommand.EndRow = Convert.ToInt16(targetCodes[1]);
                    stackerCraneTaskCommand.EndColumn = Convert.ToInt16(targetCodes[2]);
                    stackerCraneTaskCommand.EndLayer = Convert.ToInt16(targetCodes[3]);
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"移库任务终点错误,起点:【{task.NextAddress}】");
                    return null;
                }
                string[] sourceCodes = task.CurrentAddress.Split("-");
                if (sourceCodes.Length == 5)
                {
                    stackerCraneTaskCommand.StartRow = Convert.ToInt16(sourceCodes[1]);
                    stackerCraneTaskCommand.StartColumn = Convert.ToInt16(sourceCodes[2]);
                    stackerCraneTaskCommand.StartLayer = Convert.ToInt16(sourceCodes[3]);
                }
                else
                {
                    //数据配置错误
                    _taskService.UpdateTaskExceptionMessage(task.TaskNum, $"移库任务起点错误,起点:【{task.CurrentAddress}】");
                    return null;
                }
            }
            return stackerCraneTaskCommand;
        }
    }
}