wanshenmean
2026-02-11 88724eca51a5863f20ee0a552af741aeebf4e8f2
Code/WCS/WIDESEAWCS_Server/WIDESEAWCS_Tasks/RobotJob/RobotJob.cs
@@ -1,7 +1,15 @@
using Quartz;
using HslCommunication;
using Newtonsoft.Json;
using Quartz;
using System.Collections.Concurrent;
using System.Net.Sockets;
using System.Text.Json;
using WIDESEAWCS_Common.HttpEnum;
using WIDESEAWCS_Core;
using WIDESEAWCS_Core.Helper;
using WIDESEAWCS_Core.Http;
using WIDESEAWCS_DTO.Stock;
using WIDESEAWCS_DTO.TaskInfo;
using WIDESEAWCS_ITaskInfoRepository;
using WIDESEAWCS_ITaskInfoService;
using WIDESEAWCS_Model.Models;
@@ -17,27 +25,28 @@
        private readonly TcpSocketServer _TcpSocket;
        private static readonly ConcurrentDictionary<string, RobotSocketState> _socketStates = new();
        private static int _eventSubscribedFlag;
        private readonly ITaskService _taskService;
        private readonly IRobotTaskService _robottaskService;
        private readonly ITaskExecuteDetailService _taskExecuteDetailService;
        private readonly ITaskRepository _taskRepository;
        private readonly IRouterService _routerService;
        public RobotJob(TcpSocketServer TcpSocket, ITaskService taskService, ITaskExecuteDetailService taskExecuteDetailService, ITaskRepository taskRepository, IRouterService routerService)
        public RobotJob(TcpSocketServer TcpSocket, IRobotTaskService RobottaskService, ITaskService TaskService)
        {
            _TcpSocket = TcpSocket;
            _taskService = taskService;
            _taskExecuteDetailService = taskExecuteDetailService;
            _taskRepository = taskRepository;
            _routerService = routerService;
            _robottaskService = RobottaskService;
            this._taskService = TaskService;
        }
        public Task Execute(IJobExecutionContext context)
        public async Task Execute(IJobExecutionContext context)
        {
            bool flag = context.JobDetail.JobDataMap.TryGetValue("JobParams", out object? value);
            RobotCraneDevice robotCrane = (RobotCraneDevice?)value ?? new RobotCraneDevice();
            if (!flag || robotCrane.IsNullOrEmpty())
            {
                return Task.CompletedTask;
                return;
            }
            string ipAddress = robotCrane.IPAddress;
@@ -56,7 +65,7 @@
            var clientIds = _TcpSocket.GetClientIds();
            if (!clientIds.Contains(ipAddress))
            {
                return Task.CompletedTask;
                return;
            }
            // 订阅一次 message 事件(全局一次)
@@ -74,13 +83,34 @@
            }
            // 获取任务并缓存到状态中
            Dt_Task? task = GetTask(robotCrane);
            Dt_RobotTask? task = GetTask(robotCrane);
            if (task != null)
            {
                state.CurrentTask = task;
                if (task.RobotTaskTotalNum != 48)
                {
                    // 处理正在执行的任务
                    if (state.RobotRunMode == 1 && state.RobotControlMode == 1)
                    {
                        await Task.Delay(1000);
                        if ((state.CurrentAction == "Homed" || state.CurrentAction == "PickFinished" || state.CurrentAction == "PutFinished") && state.OperStatus == "Running")
                        {
                            // TODO 读取线体电池条码,发送取电池指令
                            if (true)
                            {
                                // 模拟读取条码
                                state.CellBarcode = new string[] { "CellBarcode1", "CellBarcode2", "CellBarcode3", "CellBarcode4" };
                                string taskString = $"Pickbattery,{task.RobotSourceAddress}";
                                // 发送任务指令
                                bool result = await _TcpSocket.SendToClientAsync(ipAddress, taskString);
                            }
                        }
                    }
                }
            }
            return Task.CompletedTask;
            return;
        }
        /// <summary>
@@ -106,7 +136,7 @@
        {
            string messageLower = message.ToLowerInvariant();
            if (IsSimpleCommand(messageLower, state))
            if (await IsSimpleCommandAsync(messageLower, state))
            {
                return null;
            }
@@ -127,13 +157,62 @@
                        if (cmd.StartsWith("pickfinished"))
                        {
                            StockDTO stockDTO = new StockDTO
                            {
                                SourceLineNo = state.CurrentTask?.RobotSourceAddressLineCode,
                                SourcePalletNo = state.CurrentTask?.RobotSourceAddressPalletCode,
                                TargetPalletNo = state.CurrentTask?.RobotTargetAddressPalletCode,
                                TargetLineNo = state.CurrentTask?.RobotTargetAddressLineCode,
                                Details = positions
                                        .Where(x => x > 0)
                                        .OrderBy(x => x)
                                        .Select((x, idx) => new StockDetailDTO
                                        {
                                            Quantity = state.CurrentTask?.RobotTaskTotalNum ?? 1,
                                            Channel = x > 0 ? x : throw new ArgumentOutOfRangeException(nameof(x), "Channel must be positive"),
                                            CellBarcode = state.CellBarcode[idx]
                                        })
                                        .ToList()
                            };
                            state.LastPickPositions = positions;
                            state.CurrentAction = "PickFinished";
                            var result = await HttpRequestHelper.HTTPPostAsync(nameof(Category.WMS), stockDTO.ToJsonString(), state.CurrentTask?.RobotTaskType == 2 ? nameof(ConfigKey.ChangePalletAsync) : nameof(ConfigKey.SplitPalletAsync));
                            if (result.Status)
                            {
                                state.CurrentAction = "PickFinished";
                            }
                        }
                        else if (cmd.StartsWith("putfinished"))
                        {
                            state.LastPutPositions = positions;
                            state.CurrentAction = "PutFinished";
                            if (state.CurrentTask?.RobotTaskType == 1)
                            {
                                // 发送数据给WMS组盘/换盘
                                StockDTO stockDTO = new StockDTO
                                {
                                    SourceLineNo = state.CurrentTask?.RobotSourceAddressLineCode,
                                    SourcePalletNo = state.CurrentTask?.RobotSourceAddressPalletCode,
                                    TargetPalletNo = state.CurrentTask?.RobotTargetAddressPalletCode,
                                    TargetLineNo = state.CurrentTask?.RobotTargetAddressLineCode,
                                    Details = positions
                                        .Where(x => x > 0)
                                        .OrderBy(x => x)
                                        .Select((x, idx) => new StockDetailDTO
                                        {
                                            Quantity = state.CurrentTask?.RobotTaskTotalNum ?? 1,
                                            Channel = x > 0 ? x : throw new ArgumentOutOfRangeException(nameof(x), "Channel must be positive"),
                                            CellBarcode = state.CellBarcode[idx]
                                        })
                                        .ToList()
                                };
                                var result = await HttpRequestHelper.HTTPPostAsync(nameof(Category.WMS), stockDTO.ToJsonString(), nameof(ConfigKey.GroupPalletAsync));
                                if (result.Status)
                                {
                                    state.CurrentAction = "PutFinished";
                                }
                            }
                        }
                    }
                }
@@ -151,7 +230,7 @@
        /// <param name="message"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        private bool IsSimpleCommand(string message, RobotSocketState state)
        private async Task<bool> IsSimpleCommandAsync(string message, RobotSocketState state)
        {
            switch (message)
            {
@@ -173,10 +252,18 @@
                case "allpickfinished":
                    state.CurrentAction = "AllPickFinished";
                    if (state.CurrentTask?.RobotTaskType == 2 || state.CurrentTask?.RobotTaskType == 3)
                    {
                        await HandleInboundTaskAsync(state, useSourceAddress: true);
                    }
                    return true;
                case "allputfinished":
                    state.CurrentAction = "AllPutFinished";
                    if (state.CurrentTask?.RobotTaskType == 1)
                    {
                        await HandleInboundTaskAsync(state, useSourceAddress: false);
                    }
                    return true;
                case "running":
@@ -199,7 +286,7 @@
                    state.RobotRunMode = 1;
                    return true;
                case "runmodemode,2":
                case "runmode,2":
                    state.RobotRunMode = 2;
                    return true;
@@ -224,6 +311,49 @@
            }
        }
        private async Task HandleInboundTaskAsync(RobotSocketState state, bool useSourceAddress)
        {
            var currentTask = state.CurrentTask;
            if (currentTask == null)
            {
                return;
            }
            string roadway = currentTask.RobotRoadway == "1" ? "GWSC001" : currentTask.RobotRoadway == "2" ? "HCSC001" : "SC001";
            int warehouseId = currentTask.RobotRoadway == "1" ? 1 : currentTask.RobotRoadway == "2" ? 2 : 3;
            CreateTaskDto taskDto = new CreateTaskDto
            {
                PalletCode = currentTask.RobotTargetAddressPalletCode ?? string.Empty,
                SourceAddress = currentTask.RobotTargetAddress ?? string.Empty,
                TargetAddress = currentTask.RobotTargetAddress ?? string.Empty,
                Roadway = roadway,
                WarehouseId = warehouseId,
                PalletType = 1,
                TaskType = 4
            };
            var result = await HttpRequestHelper.HTTPPostAsync(nameof(Category.WMS), taskDto.ToJsonString(), nameof(ConfigKey.CreateTaskInboundAsync));
            if (!result.Status)
            {
                return;
            }
            WMSTaskDTO taskDTO = JsonConvert.DeserializeObject<WMSTaskDTO>(result.Data.ToString() ?? string.Empty) ?? new WMSTaskDTO();
            var content = _taskService.ReceiveWMSTask(new List<WMSTaskDTO> { taskDTO });
            if (!content.Status) return;
            var taskInfo = _taskService.QueryByTaskNum(taskDTO.TaskNum);
            string targetAddress = useSourceAddress ? taskDTO.SourceAddress : taskDTO.TargetAddress;
            IDevice? device = Storage.Devices.Where(x => x.DeviceProDTOs.Select(x => x.DeviceChildCode == taskDTO.SourceAddress).FirstOrDefault()).FirstOrDefault() ?? null;
            device?.Communicator.Write(nameof(ConveyorLineDBNameNew.Target), taskInfo.NextAddress);
            device?.Communicator.Write(nameof(ConveyorLineDBNameNew.TaskNo), taskDTO.TaskNum);
            device?.Communicator.Write(nameof(ConveyorLineDBNameNew.WCS_STB), 1);
        }
        /// <summary>
        /// 机械手前缀命令处理
        /// </summary>
@@ -234,9 +364,9 @@
            return message.StartsWith("pickfinished") || message.StartsWith("putfinished");
        }
        private Dt_Task? GetTask(RobotCraneDevice robotCrane)
        private Dt_RobotTask? GetTask(RobotCraneDevice robotCrane)
        {
            return _taskService.QueryRobotCraneTask(robotCrane.DeviceCode);
            return _robottaskService.QueryRobotCraneTask(robotCrane.DeviceCode);
        }
    }
@@ -290,8 +420,13 @@
        public int[]? LastPutPositions { get; set; }
        /// <summary>
        /// 抓取位置条码
        /// </summary>
        public string[] CellBarcode { get; set; }
        /// <summary>
        /// 当前抓取任务
        /// </summary>
        public Dt_Task? CurrentTask { get; set; }
        public Dt_RobotTask? CurrentTask { get; set; }
    }
}