RobotController.cs 20.9 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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
using Microsoft.AspNetCore.Mvc;
using Rcs.Application.Common;
using Rcs.Application.DTOs;
using MassTransit.Mediator;
using Rcs.Application.MessageBus.Commands;
using Rcs.Application.MessageBus.Responses;
using Rcs.Application.Services.PathFind.Models;
using Rcs.Domain.Repositories;
using Rcs.Domain.Settings;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
using System.Text.Json;
using Rcs.Infrastructure.MessageBus.Handlers.Commands;
using StatusCodes = Microsoft.AspNetCore.Http.StatusCodes;

namespace Rcs.Api.Controllers
{
    /// <summary>
    /// 机器人管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class RobotController : ControllerBase
    {
        private readonly ILogger<RobotController> _logger;
        private readonly IMediator _mediator;
        private readonly IRobotRepository _robotRepository;
        private readonly IConnectionMultiplexer _redis;
        private readonly AppSettings _settings;

        public RobotController(
            ILogger<RobotController> logger,
            IMediator mediator,
            IRobotRepository robotRepository,
            IConnectionMultiplexer redis,
            IOptions<AppSettings> settings)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _mediator = mediator;
            _robotRepository = robotRepository;
            _redis = redis;
            _settings = settings.Value;
        }

        /// <summary>
        /// 获取机器人列表
        /// </summary>
        /// <returns>机器人列表</returns>
        [HttpGet("list")]
        public async Task<IActionResult> GetRobotList([FromQuery] GetRobotsQuery query, CancellationToken cancellationToken = default)
        {
            var client = _mediator.CreateRequestClient<GetRobotsQuery>();
            var response = await client.GetResponse<PagedResponse<RobotListItemDto>>(query, cancellationToken);
            return Ok(response.Message);
        }

        /// <summary>
        /// 根据ID获取机器人详情
        /// </summary>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>机器人详情</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetRobotById(string id, CancellationToken cancellationToken = default)
        {
            if(!Guid.TryParse(id, out Guid robotId))
            {
                return BadRequest(ApiResponse.Failed("无效的机器人ID格式", StatusCodes.Status400BadRequest));
            }
            var client = _mediator.CreateRequestClient<GetRobotQuery>();
            var response = await client.GetResponse<ApiResponse<RobotDto>>(new GetRobotQuery()
            {
                RobotId = robotId
            }, cancellationToken);

            return Ok(response.Message);
        }

        /// <summary>
        /// 创建机器人
        /// </summary>
        /// <param name="command">创建命令</param>
        /// <returns>创建的机器人信息</returns>
        [HttpPost]
        public async Task<IActionResult> CreateOrUpdateRobot([FromBody] CreateOrUpdateRobotCommand command)
        {
            /*
             test model
             {
              "robotCode": "1001",
              "robotName": "ROBOT",
              "robotVersion": "2.0.0",
              "protocolName": "VDA",
              "protocolVersion": "2.0.0",
              "robotManufacturer": "HuaHeng",
              "robotSerialNumber": "1001",
              "robotType": 1,
              "isOmnidirectional": true,
              "active": true
            }
             */
            var client = _mediator.CreateRequestClient<CreateOrUpdateRobotCommand>();
            var response = await client.GetResponse<ApiResponse>(command);
            
            return Ok(response.Message);
        }
        /// <summary>
        /// 根据ID获取机器人详情
        /// </summary>
        /// <param name="query"></param>
        /// <param name="cancellationToken"></param>
        /// <returns>机器人详情</returns>
        [HttpPost("{id}")]
        public async Task<IActionResult> DeleteRobotById(string id, CancellationToken cancellationToken = default)
        {
            if(!Guid.TryParse(id, out Guid robotId))
            {
                return BadRequest(ApiResponse.Failed("无效的机器人ID格式", StatusCodes.Status400BadRequest));
            }
            var client = _mediator.CreateRequestClient<DeleteRobotCommand>();
            var response = await client.GetResponse<ApiResponse>(new DeleteRobotCommand()
            {
                RobotId = robotId
            }, cancellationToken);
            
            return Ok(response.Message);
        }

        /// <summary>
        /// 复位指定机器人
        /// @author zzy
        /// </summary>
        /// <param name="id">机器人ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        [HttpPost("{id}/reset")]
        public async Task<IActionResult> ResetRobot(string id, CancellationToken cancellationToken = default)
        {
            if (!Guid.TryParse(id, out Guid robotId))
            {
                return BadRequest(ApiResponse.Failed("无效的机器人ID格式", StatusCodes.Status400BadRequest));
            }
            var client = _mediator.CreateRequestClient<ResetRobotCommand>();
            var response = await client.GetResponse<ApiResponse>(new ResetRobotCommand { RobotId = robotId }, cancellationToken);
            return Ok(response.Message);
        }

        /// <summary>
        /// 取消指定机器人的任务
        /// @author zzy
        /// </summary>
        /// <param name="id">机器人ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        [HttpPost("{id}/cancel-task")]
        public async Task<IActionResult> CancelRobotTask(string id, CancellationToken cancellationToken = default)
        {
            if (!Guid.TryParse(id, out Guid robotId))
            {
                return BadRequest(ApiResponse.Failed("无效的机器人ID格式", StatusCodes.Status400BadRequest));
            }
            var client = _mediator.CreateRequestClient<CancelRobotTaskCommand>();
            var response = await client.GetResponse<ApiResponse>(new CancelRobotTaskCommand { RobotId = robotId }, cancellationToken);
            return Ok(response.Message);
        }
        /// <summary>
        /// 暂停机器人
        /// @author zzy
        /// </summary>
        /// <param name="id">机器人ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        [HttpPost("{id}/pause")]
        public async Task<IActionResult> RobotPause(string id, CancellationToken cancellationToken = default)
        {
            if (!Guid.TryParse(id, out Guid robotId))
            {
                return BadRequest(ApiResponse.Failed("无效的机器人ID格式", StatusCodes.Status400BadRequest));
            }
            var client = _mediator.CreateRequestClient<PauseRobotCommand>();
            var response = await client.GetResponse<ApiResponse>(new PauseRobotCommand { RobotId = robotId }, cancellationToken);
            return Ok(response.Message);
        }
        /// <summary>
        /// 取消暂停机器人
        /// @author zzy
        /// </summary>
        /// <param name="id">机器人ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        [HttpPost("{id}/unpause")]
        public async Task<IActionResult> RobotUnPause(string id, CancellationToken cancellationToken = default)
        {
            if (!Guid.TryParse(id, out Guid robotId))
            {
                return BadRequest(ApiResponse.Failed("无效的机器人ID格式", StatusCodes.Status400BadRequest));
            }
            var client = _mediator.CreateRequestClient<UnPauseRobotCommand>();
            var response = await client.GetResponse<ApiResponse>(new UnPauseRobotCommand { RobotId = robotId }, cancellationToken);
            return Ok(response.Message);
        }

        /// <summary>
        /// 重定位机器人
        /// @author zzy
        /// </summary>
        /// <param name="id">机器人ID</param>
        /// <param name="request">重定位请求(包含x, y, theta)</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        [HttpPost("{id}/relocate")]
        public async Task<IActionResult> RelocateRobot(string id, [FromBody] RelocationCommand request, CancellationToken cancellationToken = default)
        {
            if (!Guid.TryParse(id, out Guid robotId))
            {
                return BadRequest(ApiResponse.Failed("无效的机器人ID格式", StatusCodes.Status400BadRequest));
            }
            var client = _mediator.CreateRequestClient<RelocationCommand>();
            var response = await client.GetResponse<ApiResponse>(request, cancellationToken);
            return Ok(response.Message);
        }

        /// <summary>
        /// 根据车体编号查询当前车辆绑定的所有VDA路径锁(严格binding索引 + 路径缓存计划)。
        /// </summary>
        /// <param name="robotCode">车体编号(robot_code)</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>锁明细</returns>
        [HttpGet("vda-path-locks")]
        public async Task<IActionResult> GetRobotVdaPathLocks([FromQuery] string robotCode, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrWhiteSpace(robotCode))
            {
                return BadRequest(ApiResponse.Failed("车体编号不能为空", StatusCodes.Status400BadRequest));
            }

            var robot = await _robotRepository.GetByRobotCodeAsync(robotCode.Trim(), cancellationToken);
            if (robot == null)
            {
                return NotFound(ApiResponse.Failed($"未找到车体编号为 {robotCode} 的机器人", StatusCodes.Status404NotFound));
            }

            var db = _redis.GetDatabase();
            var response = new RobotVdaPathLocksResponse
            {
                RobotId = robot.RobotId,
                RobotCode = robot.RobotCode,
                QueriedAt = DateTime.Now
            };

            var bindingSetKey = $"{_settings.Redis.KeyPrefixes.RobotLockResourcesPrefix}:{robot.RobotId}:{_settings.Redis.KeyPrefixes.RobotLockBindingsSuffix}";
            var bindingIndexKeys = (await db.SetMembersAsync(bindingSetKey))
                .Select(v => v.ToString())
                .Where(v => !string.IsNullOrWhiteSpace(v))
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();

            var cachePlans = await LoadRobotActiveLockPlansFromPathCacheAsync(robot.RobotId, db);
            var cachePlanLookup = cachePlans
                .GroupBy(plan => plan.BindingId, StringComparer.OrdinalIgnoreCase)
                .ToDictionary(group => group.Key, group => group.OrderByDescending(x => x.CacheCreatedAt).First(), StringComparer.OrdinalIgnoreCase);

            var indexedBindingIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            foreach (var bindingIndexKey in bindingIndexKeys)
            {
                var bindingId = TryExtractBindingIdFromBindingIndexKey(bindingIndexKey, bindingSetKey);
                if (string.IsNullOrWhiteSpace(bindingId))
                {
                    continue;
                }

                indexedBindingIds.Add(bindingId);
                var resourceKeys = (await db.SetMembersAsync(bindingIndexKey))
                    .Select(v => v.ToString())
                    .Where(v => !string.IsNullOrWhiteSpace(v))
                    .Distinct(StringComparer.OrdinalIgnoreCase)
                    .ToList();

                cachePlanLookup.TryGetValue(bindingId, out var cachePlan);
                response.Bindings.Add(BuildLockItem(bindingId, bindingIndexKey, resourceKeys, cachePlan, true));
            }

            // 兜底展示:路径缓存中仍标记活跃,但未出现在严格binding索引中的计划。
            foreach (var plan in cachePlans.Where(plan => !indexedBindingIds.Contains(plan.BindingId)))
            {
                response.Bindings.Add(BuildLockItem(
                    plan.BindingId,
                    null,
                    new List<string>(),
                    plan,
                    false));
            }

            response.BindingCount = response.Bindings.Count;
            response.IndexedBindingCount = response.Bindings.Count(x => x.IsIndexedInRedis);
            response.CacheOnlyBindingCount = response.BindingCount - response.IndexedBindingCount;

            return Ok(ApiResponse<RobotVdaPathLocksResponse>.Successful(response));
        }

        private async Task<List<PathCacheLockPlanItem>> LoadRobotActiveLockPlansFromPathCacheAsync(Guid robotId, IDatabase db)
        {
            var result = new List<PathCacheLockPlanItem>();
            var endpoints = _redis.GetEndPoints();
            if (endpoints.Length == 0)
            {
                return result;
            }

            var server = _redis.GetServer(endpoints.First());
            var pattern = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robotId}:*";
            var cacheKeys = server.Keys(pattern: pattern).ToArray();

            foreach (var cacheKey in cacheKeys)
            {
                var keyText = cacheKey.ToString();
                if (!IsVdaPathCachePayloadKey(keyText, robotId))
                {
                    continue;
                }

                var cacheData = await db.StringGetAsync(cacheKey);
                if (cacheData.IsNullOrEmpty)
                {
                    continue;
                }

                VdaSegmentedPathCache? cache;
                try
                {
                    cache = JsonSerializer.Deserialize<VdaSegmentedPathCache>(cacheData.ToString());
                }
                catch (Exception ex) when (ex is JsonException or NotSupportedException)
                {
                    _logger.LogWarning(ex, "查询VDA路径锁时反序列化失败: CacheKey={CacheKey}", keyText);
                    continue;
                }

                if (cache == null)
                {
                    continue;
                }

                TryExtractTaskAndSubTaskIds(keyText, out var taskId, out var subTaskId);
                foreach (var plan in cache.LockBindingPlans.Where(x => x.IsLocked && !x.IsReleased))
                {
                    result.Add(new PathCacheLockPlanItem
                    {
                        BindingId = plan.BindingId,
                        BindingType = plan.BindingType.ToString(),
                        AnchorCode = plan.AnchorCode,
                        JunctionIndex = plan.JunctionIndex,
                        ResourceIndex = plan.ResourceIndex,
                        OrderIndex = plan.OrderIndex,
                        ReleaseTriggerNodeCode = plan.ReleaseTriggerNodeCode,
                        CoveredNodeCodes = plan.CoveredNodeCodes.ToList(),
                        CoveredEdgeCodes = plan.CoveredEdgeCodes.ToList(),
                        LockedAt = plan.LockedAt,
                        ReleasedAt = plan.ReleasedAt,
                        CacheKey = keyText,
                        CacheTaskId = taskId,
                        CacheSubTaskId = subTaskId,
                        CacheCreatedAt = cache.CreatedAt
                    });
                }
            }

            return result;
        }

        private static RobotVdaPathLockItem BuildLockItem(
            string bindingId,
            string? bindingIndexKey,
            IReadOnlyCollection<string> resourceKeys,
            PathCacheLockPlanItem? cachePlan,
            bool isIndexedInRedis)
        {
            var nodeResourceKeys = resourceKeys
                .Where(key => key.Contains(":lock:node:", StringComparison.OrdinalIgnoreCase))
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();
            var edgeResourceKeys = resourceKeys
                .Where(key => key.Contains(":lock:edge:", StringComparison.OrdinalIgnoreCase))
                .Distinct(StringComparer.OrdinalIgnoreCase)
                .ToList();

            return new RobotVdaPathLockItem
            {
                BindingId = bindingId,
                IsIndexedInRedis = isIndexedInRedis,
                BindingIndexKey = bindingIndexKey,
                ResourceKeys = resourceKeys.ToList(),
                NodeResourceKeys = nodeResourceKeys,
                EdgeResourceKeys = edgeResourceKeys,
                ResourceCount = resourceKeys.Count,
                NodeResourceCount = nodeResourceKeys.Count,
                EdgeResourceCount = edgeResourceKeys.Count,
                PathCachePlan = cachePlan
            };
        }

        private static string? TryExtractBindingIdFromBindingIndexKey(string bindingIndexKey, string bindingSetKey)
        {
            if (string.IsNullOrWhiteSpace(bindingIndexKey) || string.IsNullOrWhiteSpace(bindingSetKey))
            {
                return null;
            }

            var prefix = $"{bindingSetKey}:";
            if (!bindingIndexKey.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ||
                bindingIndexKey.Length <= prefix.Length)
            {
                return null;
            }

            return bindingIndexKey.Substring(prefix.Length);
        }

        private static bool IsVdaPathCachePayloadKey(string keyText, Guid robotId)
        {
            if (string.IsNullOrWhiteSpace(keyText) ||
                keyText.EndsWith(":planVersion", StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            var parts = keyText.Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
            if (parts.Length < 3)
            {
                return false;
            }

            if (!Guid.TryParse(parts[^3], out var keyRobotId) || keyRobotId != robotId)
            {
                return false;
            }

            return Guid.TryParse(parts[^2], out _) && Guid.TryParse(parts[^1], out _);
        }

        private static void TryExtractTaskAndSubTaskIds(string keyText, out Guid? taskId, out Guid? subTaskId)
        {
            taskId = null;
            subTaskId = null;

            if (string.IsNullOrWhiteSpace(keyText))
            {
                return;
            }

            var parts = keyText.Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
            if (parts.Length < 2)
            {
                return;
            }

            if (Guid.TryParse(parts[^2], out var parsedTaskId))
            {
                taskId = parsedTaskId;
            }

            if (Guid.TryParse(parts[^1], out var parsedSubTaskId))
            {
                subTaskId = parsedSubTaskId;
            }
        }
    }

    public sealed class RobotVdaPathLocksResponse
    {
        public Guid RobotId { get; set; }
        public string RobotCode { get; set; } = string.Empty;
        public int BindingCount { get; set; }
        public int IndexedBindingCount { get; set; }
        public int CacheOnlyBindingCount { get; set; }
        public DateTime QueriedAt { get; set; }
        public List<RobotVdaPathLockItem> Bindings { get; set; } = new();
    }

    public sealed class RobotVdaPathLockItem
    {
        public string BindingId { get; set; } = string.Empty;
        public bool IsIndexedInRedis { get; set; }
        public string? BindingIndexKey { get; set; }
        public int ResourceCount { get; set; }
        public int NodeResourceCount { get; set; }
        public int EdgeResourceCount { get; set; }
        public List<string> ResourceKeys { get; set; } = new();
        public List<string> NodeResourceKeys { get; set; } = new();
        public List<string> EdgeResourceKeys { get; set; } = new();
        public PathCacheLockPlanItem? PathCachePlan { get; set; }
    }

    public sealed class PathCacheLockPlanItem
    {
        public string BindingId { get; set; } = string.Empty;
        public string BindingType { get; set; } = string.Empty;
        public string AnchorCode { get; set; } = string.Empty;
        public int JunctionIndex { get; set; }
        public int ResourceIndex { get; set; }
        public int OrderIndex { get; set; }
        public string? ReleaseTriggerNodeCode { get; set; }
        public List<string> CoveredNodeCodes { get; set; } = new();
        public List<string> CoveredEdgeCodes { get; set; } = new();
        public DateTime? LockedAt { get; set; }
        public DateTime? ReleasedAt { get; set; }
        public string CacheKey { get; set; } = string.Empty;
        public Guid? CacheTaskId { get; set; }
        public Guid? CacheSubTaskId { get; set; }
        public DateTime CacheCreatedAt { get; set; }
    }
}