TaskExecutionBackgroundService.cs 16 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Rcs.Application.Services;
using Rcs.Application.Services.PathFind;
using Rcs.Application.Services.PathFind.Models;
using Rcs.Application.Services.Protocol;
using Rcs.Application.Shared;
using Rcs.Domain.Entities;
using Rcs.Domain.Enums;
using Rcs.Domain.Models.VDA5050;
using Rcs.Domain.Repositories;
using Rcs.Domain.Settings;
using Rcs.Infrastructure.PathFinding.Services;
using StackExchange.Redis;
using System.Text.Json;
using Newtonsoft.Json;
using TaskStatus = Rcs.Domain.Entities.TaskStatus;

namespace Rcs.Infrastructure.Services
{
    /// <summary>
    /// 后台任务执行服务 - 将已分配的任务下发给空闲机器人执行
    /// @author zzy
    /// </summary>
    public class TaskExecutionBackgroundService : BackgroundService, ITaskExecutionService
    {
        private readonly ILogger<TaskExecutionBackgroundService> _logger;
        private readonly IServiceScopeFactory _serviceScopeFactory;
        private readonly IRobotCacheService _robotCacheService;
        private readonly IAgvPathService _agvPathService;
        private readonly IConnectionMultiplexer _redis;
        private readonly AppSettings _settings;
        private readonly TimeSpan _executionInterval = TimeSpan.FromSeconds(2);
        private const int MaxAssignedTasksPerCycle = 10;
        

        public TaskExecutionBackgroundService(
            ILogger<TaskExecutionBackgroundService> logger,
            IServiceScopeFactory serviceScopeFactory,
            IRobotCacheService robotCacheService,
            IAgvPathService agvPathService,
            IConnectionMultiplexer redis,
            IOptions<AppSettings> settings)
        {
            _logger = logger;
            _serviceScopeFactory = serviceScopeFactory;
            _robotCacheService = robotCacheService;
            _agvPathService = agvPathService;
            _redis = redis;
            _settings = settings.Value;
        }

        /// <summary>
        /// 后台服务执行入口
        /// @author zzy
        /// </summary>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("[任务执行] 后台任务执行服务已启动");

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    await ExecuteTasksAsync(stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "[任务执行] 执行过程发生异常");
                }

                await Task.Delay(_executionInterval, stoppingToken);
            }

            _logger.LogInformation("[任务执行] 后台任务执行服务已停止");
        }

        /// <summary>
        /// 执行一次任务执行检查
        /// @author zzy
        /// </summary>
        public async Task<TaskExecutionResult> ExecuteTasksAsync(CancellationToken cancellationToken = default)
        {
            using var scope = _serviceScopeFactory.CreateScope();
            var taskRepo = scope.ServiceProvider.GetRequiredService<IRobotTaskRepository>();
            var robotRepo = scope.ServiceProvider.GetRequiredService<IRobotRepository>();

            // 1. 获取已分配和执行中的任务(执行中的任务可能有待执行的子任务)
            var assignedTasks = await taskRepo.GetByStatusAsync(TaskStatus.Assigned, cancellationToken);
            var inProgressTasks = await taskRepo.GetByStatusAsync(TaskStatus.InProgress, cancellationToken);
            
            var activeTasks = assignedTasks
                .Concat(inProgressTasks)
                .Where(t => t.RobotId.HasValue)
                .Where(t => t.SubTasks.Any())
                .ToList();

            if (!activeTasks.Any())
            {
                return new TaskExecutionResult { Success = true, ExecutedCount = 0, Message = "无待执行任务" };
            }

            var tasksToExecute = await BuildExecutionQueueAsync(activeTasks, robotRepo, taskRepo, cancellationToken);
            _logger.LogInformation("执行队列{queue}",JsonConvert.SerializeObject(tasksToExecute.Select(t => t.ShelfCode)));
            if (!tasksToExecute.Any())
            {
                return new TaskExecutionResult { Success = true, ExecutedCount = 0, Message = "无待执行任务" };
            }

            int executedCount = 0;

            foreach (var task in tasksToExecute)
            {
                if (!task.RobotId.HasValue) continue;

                // 2. 获取机器人信息
                var robot = await robotRepo.GetByIdFullDataAsync(task.RobotId.Value, cancellationToken);
                if (robot == null)
                {
                    _logger.LogWarning("[任务执行] 任务 {TaskCode} 对应的机器人不存在", task.TaskCode);
                    continue;
                }

                if (!robot.IsRobotAvailable())
                {
                    _logger.LogDebug("[任务执行] 机器人 {RobotCode} 当前不可用", robot.RobotCode);
                    continue;
                }

                // 4. 检查机器人是否有执行中的任务
                var hasInProgressTask = await HasInProgressTaskAsync(robot.RobotId, task.TaskId, taskRepo, cancellationToken);
                
                if (hasInProgressTask)
                {
                    _logger.LogDebug("[任务执行] 机器人 {RobotCode} 存在执行中任务", robot.RobotCode);
                    continue;
                }

                // 5. 根据协议类型执行任务
                var success = await ExecuteTaskByProtocolAsync(task, robot, taskRepo, scope, cancellationToken);
                if (success)
                {
                    executedCount++;
                }
            }

            return new TaskExecutionResult
            {
                Success = true,
                ExecutedCount = executedCount,
                Message = $"本次执行完成,已下发 {executedCount} 个任务"
            };
        }

        /// <summary>
        /// 构建执行队列:按机器人分组后,为每台机器人挑选一个最优候选任务。
        /// 候选任务只按“当前位置到目标点距离”排序(不进行路径重合率评估)。
        /// </summary>
        /// <param name="activeTasks">当前活动任务集合(Assigned + InProgress)</param>
        /// <param name="robotRepo">机器人仓储</param>
        /// <param name="taskRepo">任务仓储</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>本轮待执行任务列表</returns>
        private async Task<List<RobotTask>> BuildExecutionQueueAsync(
            IEnumerable<RobotTask> activeTasks,
            IRobotRepository robotRepo,
            IRobotTaskRepository taskRepo,
            CancellationToken cancellationToken)
        {
            var selectedCandidates = new List<TaskCandidate>();

            // 按机器人分组,每个机器人每轮最多选择一个“下一下发任务”
            var taskGroups = activeTasks
                .Where(t => t.RobotId.HasValue)
                .GroupBy(t => t.RobotId!.Value);

            foreach (var taskGroup in taskGroups)
            {
                var robot = await robotRepo.GetByIdFullDataAsync(taskGroup.Key, cancellationToken);
                if (robot == null)
                {
                    continue;
                }
                // 判断机器人是否仍在执行:只看“执行中子任务”,不依赖主任务状态
                var hasInProgressSubTask = taskGroup.Any(t =>
                    t.SubTasks.Any(st => st.Status == TaskStatus.InProgress));
                if (hasInProgressSubTask)
                {
                    continue;
                }

                var candidateTasks = new List<TaskCandidate>();
                foreach (var task in taskGroup)
                {
                    var taskWithDetails = await taskRepo.GetByIdWithDetailsAsync(task.TaskId, cancellationToken);
                    if (taskWithDetails == null)
                    {
                        continue;
                    }

                    if (!taskWithDetails.SubTasks.Any() && taskWithDetails.Status == TaskStatus.InProgress)
                    {
                        continue;
                    }

                    var nextSubTask = taskWithDetails.GetNextExecutableSubTask();
                    if (taskWithDetails.SubTasks.Any() && nextSubTask == null)
                    {
                        continue;
                    }

                    var distance = CalculateDistanceToTask(robot, taskWithDetails, nextSubTask);
                    candidateTasks.Add(new TaskCandidate(taskWithDetails, distance));
                }

                if (!candidateTasks.Any())
                {
                    continue;
                }

                // 仅按优先级、距离与创建时间做稳定排序
                var selectedTask = candidateTasks
                    .OrderBy(c => c, TaskCandidateComparer.Instance)
                    .FirstOrDefault();

                if (selectedTask != null)
                {
                    selectedCandidates.Add(selectedTask);
                }
            }

            return selectedCandidates
                .OrderBy(c => c, TaskCandidateComparer.Instance)
                .Select(c => c.Task)
                .Take(MaxAssignedTasksPerCycle)
                .ToList();
        }

        /// <summary>
        /// 计算机器人到候选任务目标点的直线距离。
        /// 若坐标或目标缺失,返回 <see cref="double.MaxValue"/>。
        /// </summary>
        /// <param name="robot">机器人实体</param>
        /// <param name="task">候选任务</param>
        /// <param name="nextSubTask">候选任务的下一子任务</param>
        /// <returns>直线距离</returns>
        private static double CalculateDistanceToTask(Robot robot, RobotTask task, RobotSubTask? nextSubTask)
        {
            var sourceX = robot.CurrentX ?? robot.MapNode?.X;
            var sourceY = robot.CurrentY ?? robot.MapNode?.Y;

            if (!sourceX.HasValue || !sourceY.HasValue)
            {
                return double.MaxValue;
            }

            var targetNode = nextSubTask?.EndNode
                ?? task.BeginLocation?.MapNode
                ?? task.EndLocation?.MapNode;
            if (targetNode == null)
            {
                return double.MaxValue;
            }

            var dx = sourceX.Value - targetNode.X;
            var dy = sourceY.Value - targetNode.Y;
            return Math.Sqrt(dx * dx + dy * dy);
        }

        /// <summary>
        /// 候选任务评分上下文。
        /// 封装单个候选任务的排序比较信息。
        /// </summary>
        private sealed class TaskCandidate
        {
            public TaskCandidate(RobotTask task, double distance)
            {
                Task = task;
                Distance = distance;
                CreatedAtMilliseconds = task.CreatedAt.Ticks / TimeSpan.TicksPerMillisecond;
            }

            public RobotTask Task { get; }
            public double Distance { get; }
            public long CreatedAtMilliseconds { get; }
        }

        /// <summary>
        /// 仅按距离、创建时间与 TaskId 做稳定排序。
        /// </summary>
        private sealed class TaskCandidateComparer : IComparer<TaskCandidate>
        {
            public static readonly TaskCandidateComparer Instance = new();

            public int Compare(TaskCandidate? x, TaskCandidate? y)
            {
                if (ReferenceEquals(x, y)) return 0;
                if (x is null) return 1;
                if (y is null) return -1;

                var distanceCompare = x.Distance.CompareTo(y.Distance);
                if (distanceCompare != 0)
                {
                    return distanceCompare;
                }

                var createdAtCompare = x.CreatedAtMilliseconds.CompareTo(y.CreatedAtMilliseconds);
                if (createdAtCompare != 0)
                {
                    return createdAtCompare;
                }

                return x.Task.TaskId.CompareTo(y.Task.TaskId);
            }
        }

        /// <summary>
        /// 检查机器人是否有执行中的任务
        /// @author zzy
        /// </summary>
        private async Task<bool> HasInProgressTaskAsync(
            Guid robotId,
            Guid taskId,
            IRobotTaskRepository taskRepo,
            CancellationToken cancellationToken)
        {
            var robotTasks = await taskRepo.GetByRobotIdAsync(robotId, cancellationToken);
            return robotTasks.Any(t =>
                t.TaskId != taskId &&
                t.SubTasks.Any(st => st.Status == TaskStatus.InProgress));
        }

        /// <summary>
        /// 根据协议类型执行任务
        /// @author zzy
        /// 重构为使用协议工厂模式
        /// </summary>
        private async Task<bool> ExecuteTaskByProtocolAsync(
            RobotTask task,
            Robot robot,
            IRobotTaskRepository taskRepo,
            IServiceScope scope,
            CancellationToken cancellationToken)
        {
            try
            {
                // 使用同一scope的taskRepo获取带详情的任务,避免跨scope实体跟踪冲突
                var taskWithDetails = await taskRepo.GetByIdWithDetailsAsync(task.TaskId, cancellationToken);
                if (taskWithDetails == null)
                {
                    _logger.LogWarning("[任务执行] 任务 {TaskCode} 详情获取失败", task.TaskCode);
                    return false;
                }
                if (taskWithDetails.SubTasks.Count <= 0 && robot.ProtocolType == ProtocolType.VDA)
                {
                    _logger.LogWarning("[任务执行] 任务 {TaskCode} 不存在子任务,执行失败", task.TaskCode);
                    return false;
                }

                // 获取协议服务工厂
                var protocolServiceFactory = scope.ServiceProvider.GetRequiredService<IProtocolServiceFactory>();
                var protocolService = protocolServiceFactory.GetService(robot);

                // 执行任务
                var res = await protocolService.PrepareSendOrderAsync(robot, taskWithDetails, cancellationToken);

                if (res.Success)
                {
                    taskWithDetails.StartExecution();
                    await taskRepo.UpdateAsync(taskWithDetails, cancellationToken);
                    await taskRepo.SaveChangesAsync(cancellationToken);
                    _logger.LogInformation("[任务执行] 任务 {TaskCode} 已下发给机器人 {RobotCode},协议类型: {ProtocolType}",
                        taskWithDetails.TaskCode, robot.RobotCode, robot.ProtocolType);
                    return true;
                }
                else
                {
                    throw new Exception(res.Message);
                }
            }
            catch (Exception ex)
            {
                try
                {
                    var taskForErrorUpdate = await taskRepo.GetByIdAsync(task.TaskId, cancellationToken);
                    if (taskForErrorUpdate != null)
                    {
                        taskForErrorUpdate.ErrorInfo = ex.ToString();
                        taskForErrorUpdate.UpdatedAt = DateTime.Now;
                        await taskRepo.UpdateAsync(taskForErrorUpdate, cancellationToken);
                        await taskRepo.SaveChangesAsync(cancellationToken);
                    }
                }
                catch (Exception updateEx)
                {
                    _logger.LogError(updateEx, "[任务执行] 任务 {TaskCode} 错误信息更新失败", task.TaskCode);
                }

                _logger.LogError(ex, "[任务执行] 任务 {TaskCode} 执行失败", task.TaskCode);
                return false;
            }
        }
    }
}