MqttMessageHandler.cs 29.1 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 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
using System.Collections.Concurrent;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MQTTnet.Client;
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.Models.VDA5050;
using Rcs.Domain.Repositories;
using Rcs.Domain.Settings;
using Rcs.Infrastructure.Mqtt.ParseFactory;
using Rcs.Infrastructure.Mqtt.ProcessorFactory;
using Rcs.Infrastructure.PathFinding.Services;
using Rcs.Infrastructure.Services.Protocol;
using StackExchange.Redis;
using Task = System.Threading.Tasks.Task;
using TaskStatus = System.Threading.Tasks.TaskStatus;

namespace Rcs.Infrastructure.Mqtt
{
    /// <summary>
    /// MQTT消息处理器,支持动态注册和动态字符串
    /// </summary>
    public class MqttMessageHandler : IMqttMessageHandler
    {
        private readonly ILogger<MqttMessageHandler> _logger;
        private readonly IServiceScopeFactory _scopeFactory;
        private readonly IStateParserFactory _stateParserFactory;
        private readonly IVisualizationParserFactory _visualizationParserFactory;
        private readonly IRobotCacheService _robotCacheService;
        private readonly IUnifiedTrafficControlService _unifiedTrafficControlService;
        private readonly IVisualizationProcessorFactory _visualizationProcessorFactory;
        private readonly ConcurrentDictionary<string, Func<string, string, string, Task<MqttHandleResult>>> _handlers;
        private readonly ConcurrentDictionary<string, int> _topicHeaderId = new()
        {
            ["connection"] = 0,
            ["state"] = 0,
            ["factsheet"] = 0,
            ["visualization"] = 0
        };
        private DateTime _lastLogTime = DateTime.MinValue;
        private readonly IConnectionMultiplexer _redis;
        private readonly AppSettings _settings;
        private readonly TimeSpan _logInterval = TimeSpan.FromSeconds(10);

        public MqttMessageHandler(
            ILogger<MqttMessageHandler> logger,
            IServiceScopeFactory scopeFactory,
            IStateParserFactory stateParserFactory,
            IVisualizationParserFactory visualizationParserFactory,
            IRobotCacheService robotCacheService,
            IUnifiedTrafficControlService unifiedTrafficControlService,
            IVisualizationProcessorFactory visualizationProcessorFactory,
            IConnectionMultiplexer redis,
            IOptions<AppSettings> settings)
        {
            _logger = logger;
            _scopeFactory = scopeFactory;
            _stateParserFactory = stateParserFactory;
            _visualizationParserFactory = visualizationParserFactory;
            _robotCacheService = robotCacheService;
            _unifiedTrafficControlService = unifiedTrafficControlService;
            _visualizationProcessorFactory = visualizationProcessorFactory;
            _handlers = new ConcurrentDictionary<string, Func<string, string, string, Task<MqttHandleResult>>>();
            _redis = redis;
            _settings = settings.Value;
            // 注册默认处理器
            RegisterDefaultHandlers();
        }

        /// <summary>
        /// 处理接收到的MQTT消息
        /// </summary>
        public async Task HandleMessageAsync(MqttApplicationMessageReceivedEventArgs e)
        {
            try
            {
                var topic = e.ApplicationMessage.Topic;
                var payload = ExtractPayload(e.ApplicationMessage);
                if (!topic.Contains("visualization"))
                {
                    var now = DateTime.Now;
                    // if (now - _lastLogTime >= _logInterval)
                    // {
                        _logger.LogInformation("[MQTT] Recive | Topic={Topic} | Payload={Payload}", topic, payload);
                        _lastLogTime = now;
                    //}
                }

                var result = await ProcessMessageAsync(topic, payload);

                if (!result.Success)
                {
                    _logger.LogWarning("[Advanced MQTT Handler] 消息处理失败 | Topic={Topic} | Error={Error}",
                        topic, result.Message);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "[Advanced MQTT Handler] 消息处理过程中发生严重错误");
            }
        }

        /// <summary>
        /// 注册消息类型处理器
        /// </summary>
        /// <param name="messageType">消息类型</param>
        /// <param name="handler">处理器函数</param>
        public void RegisterHandler(string messageType, Func<string, string, string, Task<MqttHandleResult>> handler)
        {
            _handlers.AddOrUpdate(messageType.ToLowerInvariant(), handler, (key, oldValue) => handler);
            _logger.LogInformation("[Advanced MQTT Handler] 注册处理器 | MessageType={MessageType}", messageType);
        }

        /// <summary>
        /// 处理消息
        /// </summary>
        private async Task<MqttHandleResult> ProcessMessageAsync(string topic, string payload)
        {
            var topicParts = topic.Split('/');

            if (topicParts.Length < 5)
            {
                return MqttHandleResult.CreateFailure($"主题格式不正确: {topic}");
            }

            var robotSerialNumber = topicParts[3];
            var messageType = topicParts[4].ToLowerInvariant();
            // robot制造商
            var robotManufacturer = topicParts[2];

            if (_handlers.TryGetValue(messageType, out var handler))
            {
                return await handler(robotManufacturer,robotSerialNumber, payload);
            }
            else
            {
                return MqttHandleResult.CreateFailure($"未找到消息类型 '{messageType}' 的处理器");
            }
        }

        /// <summary>
        /// 注册默认处理器
        /// </summary>
        private void RegisterDefaultHandlers()
        {
            RegisterHandler("connection", HandleConnectionMessageAsync);
            RegisterHandler("state", HandleStateMessageAsync);
            RegisterHandler("factsheet", HandleFactsheetMessageAsync);
            RegisterHandler("visualization", HandleVisualizationMessageAsync);
        }

        /// <summary>
        /// 处理连接状态消息
        /// </summary>
        private async Task<MqttHandleResult> HandleConnectionMessageAsync(string robotManufacturer, string robotSerialNumber, string payload)
        {
            try
            {
                var connectionInfo = JsonSerializer.Deserialize<Connection>(payload);
                if (connectionInfo == null) throw new Exception();
                // 重置该机器人所有topic的headerId为0
                if (!string.IsNullOrEmpty(robotManufacturer) && !string.IsNullOrEmpty(robotSerialNumber))
                {
                    await ResetHeaderIdsAsync(robotManufacturer,robotSerialNumber);
                }
                var robotStatus = connectionInfo.ConnectionState switch
                {
                    "ONLINE" => OnlineStatus.Online,
                    "OFFLINE" => OnlineStatus.Offline,
                    "CONNECTIONBROKEN" => OnlineStatus.Connectionbroken,
                    _ => OnlineStatus.Offline
                };

                return MqttHandleResult.CreateSuccess($"更新机器人连接状态: {robotSerialNumber} -> {connectionInfo.ConnectionState}");

            }
            catch (Exception ex)
            {
                return MqttHandleResult.CreateFailure($"处理MQTT连接消息失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 处理状态消息(直接使用制造商+序列号更新缓存)
        /// @author zzy
        /// </summary>
        private async Task<MqttHandleResult> HandleStateMessageAsync(string robotManufacturer, string robotSerialNumber, string payload)
        {
            try
            {
                
                // 使用工厂解析特定制造商的状态数据
                var stateInfo = _stateParserFactory.ParseState(robotManufacturer, payload);
                if (stateInfo == null) throw new Exception("状态数据解析失败");
                // 可选:进行headerId去重判断
                if (!await IsNewHeaderIdAsync("state", robotManufacturer, robotSerialNumber, stateInfo.HeaderId))
                    throw new Exception($"状态消息HeaderId: {stateInfo.HeaderId} 消息过期");
                // 解析状态
                var robotStatus = DetermineRobotStatus(stateInfo);
                var operatingMode = ParseOperatingMode(stateInfo.OperatingMode);
                var errors = stateInfo.Errors.Any() ? JsonSerializer.Serialize(stateInfo.Errors) : null;
                var previousStatus = await _robotCacheService.GetStatusAsync(robotManufacturer, robotSerialNumber);
                var previousLastNode = previousStatus?.LastNode;

                // 直接使用制造商+序列号更新状态到Redis缓存
                await _robotCacheService.UpdateStatusAsync(
                    robotManufacturer,
                    robotSerialNumber,
                    robotStatus,
                    OnlineStatus.Online,
                    (int?)stateInfo.BatteryState?.BatteryCharge,
                    stateInfo.Driving,
                    stateInfo.Paused,
                    stateInfo.BatteryState?.Charging,
                    operatingMode,
                    errors,
                    stateInfo.LastNodeId);
                
                // 状态上报时尝试续期路径锁(无论是否行驶,拥堵等待时也可能仍占用路径)
                // RenewAllRobotLocksAsync 仅会续期该机器人当前持有的锁,无锁时不会产生副作用
                // @author zzy
                // @date 2026-03-05
                var basicInfo = await _robotCacheService.GetBasicAsync(robotManufacturer, robotSerialNumber);
                if (basicInfo != null && Guid.TryParse(basicInfo.RobotId, out var robotId))
                {
                    if (!string.Equals(previousLastNode, stateInfo.LastNodeId, StringComparison.OrdinalIgnoreCase))
                    {
                        await ReleaseExecutedLocksBeforeLastNodeAsync(robotId, stateInfo.LastNodeId);
                    }

                    await _unifiedTrafficControlService.RenewAllRobotLocksAsync(robotId, 30);
                }

                // 处理NewBaseRequest:当车辆快到当前段终点时,判断并发送下一段路径指令
                //if ((bool)stateInfo.NewBaseRequest)
                //{
                    await HandleNewBaseRequestAsync(robotManufacturer, robotSerialNumber);
                //}

                // VDA5050 Order 完成自动判断
                // 条件预筛选:仅在机器人空闲(非行驶、非错误)时进行完成判断
                // 注意:原地路径场景下 State.OrderId 可能不是当前子任务,不能作为硬条件
                // @author zzy
                if (!stateInfo.Driving && robotStatus != RobotStatus.Error
                )
                {
                    var hasInProgressTask = await HasInProgressTaskWithInProgressSubTaskAsync(
                        robotManufacturer,
                        robotSerialNumber);

                    if (hasInProgressTask)
                    {
                        await TryHandleOrderCompletionAsync(robotManufacturer, robotSerialNumber, stateInfo);
                    }
                }

                return MqttHandleResult.CreateSuccess($"成功更新机器人状态: {robotManufacturer}:{robotSerialNumber}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理制造商 '{Manufacturer}' 的状态消息失败", robotManufacturer);
                return MqttHandleResult.CreateFailure($"处理状态消息失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 处理设备信息消息
        /// </summary>
        private Task<MqttHandleResult> HandleFactsheetMessageAsync(string robotManufacturer, string robotSerialNumber, string payload)
        {
            try
            {
                //var factSheet = JsonSerializer.Deserialize<FactSheet>(payload);
                //if (factSheet == null) throw new SharedException(10001);
                //if (!IsNewHeaderId("factsheet", factSheet.HeaderId)) throw new SharedException(10002);

                //using var scope = _serviceProvider.CreateScope();
                //var robotRepository = scope.ServiceProvider.GetRequiredService<IRobotRepository>();

                //var robot = await robotRepository.GetBySerialNumberAsync(robotSerialNumber);
                //if (robot == null)
                //{
                //    throw new ExtendRobotException(robotSerialNumber, 20003);
                //}
                //robot.UpdateFactSheet(factSheet);
                //await robotRepository.UpdateAsync(robot);

                return Task.FromResult(MqttHandleResult.CreateSuccess());
            }
            catch (Exception ex)
            {
                return Task.FromResult(MqttHandleResult.CreateFailure($"处理设备信息失败: {ex.Message}", ex));
            }
        }

        /// <summary>
        /// 处理可视化消息 - 解析后委托给制造商专用处理器
        /// @author zzy
        /// </summary>
        private async Task<MqttHandleResult> HandleVisualizationMessageAsync(string robotManufacturer, string robotSerialNumber, string payload)
        {
            try
            {
                // 第一步:通过工厂按制造商解析可视化数据
                var visualization = _visualizationParserFactory.ParseVisualization(robotManufacturer, payload);
                if (visualization == null)
                    return MqttHandleResult.CreateFailure("可视化数据解析失败");

                // 第二步:headerId去重判断
                if (!await IsNewHeaderIdAsync("visualization", robotManufacturer, robotSerialNumber, visualization.HeaderId))
                    return MqttHandleResult.CreateFailure($"可视化消息HeaderId: {visualization.HeaderId} 消息过期");

                // 第三步:委托给制造商专用处理器处理数据
                var processor = _visualizationProcessorFactory.GetProcessor(robotManufacturer);
                var processResult = await processor.ProcessAsync(robotManufacturer, robotSerialNumber, visualization);

                if (!processResult.Success)
                {
                    _logger.LogWarning(
                        "可视化数据处理失败: Robot={Manufacturer}:{SerialNumber}, Message={Message}",
                        robotManufacturer, robotSerialNumber, processResult.Message);
                }

                return MqttHandleResult.CreateSuccess(
                    $"可视化消息处理完成: {robotManufacturer}:{robotSerialNumber}");
            }
            catch (Exception ex)
            {
                return MqttHandleResult.CreateFailure($"处理可视化消息失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 从MQTT消息中提取载荷,并将Unicode转义序列转换为正常UTF-8字符
        /// </summary>
        private static string ExtractPayload(MQTTnet.MqttApplicationMessage message)
        {
            if (message.PayloadSegment.Array is not { } arr)
            {
                return string.Empty;
            }

            // 1. 将字节数组解码为UTF-8字符串
            var rawString = System.Text.Encoding.UTF8.GetString(
                arr, 
                message.PayloadSegment.Offset, 
                message.PayloadSegment.Count);

            // 2. 将Unicode转义序列(\uXXXX)转换为正常字符
            return System.Text.RegularExpressions.Regex.Replace(
                rawString,
                @"\\u([0-9a-fA-F]{4})",
                match => ((char)Convert.ToInt32(match.Groups[1].Value, 16)).ToString());
        }

        private string BuildHeaderHashKey(string robotManufacturer, string robotSN)
        {
            return $"{_settings.Redis.KeyPrefixes.Robot}:{robotManufacturer}:{robotSN}:{_settings.Redis.KeyPrefixes.MqttHeaderSuffix}";
        }

        // 基于Redis按机器人维度检查并更新headerId
        private async Task<bool> IsNewHeaderIdAsync(string topic, string robotManufacturer,string robotSN, int newHeaderId)
        {
            try
            {
                var redisDb = _redis.GetDatabase();
                var key = BuildHeaderHashKey(robotManufacturer,robotSN);
                var field = topic.ToLowerInvariant();

                var currentValue = await redisDb.HashGetAsync(key, field);
                var currentHeaderId = 0;
                if (currentValue.HasValue && int.TryParse(currentValue.ToString(), out var parsed))
                {
                    currentHeaderId = parsed;
                }
                
                if (newHeaderId > currentHeaderId)
                {
                    await redisDb.HashSetAsync(key, field, newHeaderId);
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查并更新机器人 {RobotCode} 的 {Topic} headerId 失败", robotManufacturer + robotSN, topic);
                return false;
            }
        }

        // 将指定机器人的所有topic headerId重置为0
        public async Task ResetHeaderIdsAsync( string robotManufacturer,string robotSN)
        {
            try
            {
                var redisDb = _redis.GetDatabase();
                var key = BuildHeaderHashKey(robotManufacturer,robotSN);
                var entries = new HashEntry[]
                {
                    new("connection", 0),
                    new("state", 0),
                    new("factsheet", 0),
                    new("visualization", 0)
                };
                await redisDb.HashSetAsync(key, entries);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重置机器人 {RobotCode} 的 headerId 失败", robotManufacturer + robotSN );
            }
        }      
        /// <summary>
        /// 根据状态信息判断Robot状态
        /// </summary>
        private RobotStatus DetermineRobotStatus(State stateInfo)
        {
            // 判断是否有致命错误
            var hasFatalError = stateInfo.Errors.Any(e =>
                e.ErrorLevel?.Equals("FATAL", StringComparison.OrdinalIgnoreCase) == true);

            if (hasFatalError)
                return RobotStatus.Error;

            // 判断是否忙碌(正在行驶或暂停)
            if (stateInfo.Driving || stateInfo.Paused == true)
                return RobotStatus.Busy;

            // 默认空闲
            return RobotStatus.Idle;
        }

        /// <summary>
        /// 解析操作模式
        /// @author zzy
        /// </summary>
        private static OperatingMode ParseOperatingMode(string? mode)
        {
            return mode?.ToUpperInvariant() switch
            {
                "AUTOMATIC" => OperatingMode.Automatic,
                "SEMIAUTOMATIC" => OperatingMode.Semiautomatic,
                "MANUAL" => OperatingMode.Manual,
                "SERVICE" => OperatingMode.Service,
                "TEACHIN" => OperatingMode.Teachin,
                _ => OperatingMode.Automatic
            };
        }

        /// <summary>
        /// 根据机器人 LastNode 在已下发且已发送的路径中释放已执行节点/边锁(不释放 LastNode 本身)
        /// 释放完成后,续期仅覆盖仍可能占用的路径锁
        /// @author zzy
        /// @date 2026-03-05
        /// </summary>
        private async Task ReleaseExecutedLocksBeforeLastNodeAsync(Guid robotId, string? lastNodeId)
        {
            if (string.IsNullOrWhiteSpace(lastNodeId))
            {
                return;
            }

            try
            {
                var endpoints = _redis.GetEndPoints();
                if (endpoints.Length == 0)
                {
                    return;
                }

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

                if (cacheKeys.Length == 0)
                {
                    return;
                }

                VdaSegmentedPathCache? activeCache = null;
                foreach (var cacheKey in cacheKeys)
                {
                    var cacheData = await db.StringGetAsync(cacheKey);
                    if (cacheData.IsNullOrEmpty)
                    {
                        continue;
                    }

                    var candidate = JsonSerializer.Deserialize<VdaSegmentedPathCache>(cacheData.ToString());
                    if (candidate == null)
                    {
                        continue;
                    }

                    if (activeCache == null || candidate.CreatedAt > activeCache.CreatedAt)
                    {
                        activeCache = candidate;
                    }
                }

                if (activeCache == null || string.IsNullOrWhiteSpace(activeCache.MapCode))
                {
                    return;
                }

                var sentSegments = activeCache.JunctionSegments
                    .SelectMany(j => j.ResourceSegments)
                    .Where(r => r.IsSent)
                    .SelectMany(r => r.Segments)
                    .ToList();

                if (sentSegments.Count == 0)
                {
                    return;
                }

                var nodeCodesToRelease = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                var edgeCodesToRelease = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                var matchedLastNode = false;

                foreach (var segment in sentSegments)
                {
                    if (string.IsNullOrWhiteSpace(segment.FromNodeCode) || string.IsNullOrWhiteSpace(segment.ToNodeCode))
                    {
                        continue;
                    }

                    if (string.Equals(segment.FromNodeCode, lastNodeId, StringComparison.OrdinalIgnoreCase))
                    {
                        matchedLastNode = true;
                        break;
                    }

                    nodeCodesToRelease.Add(segment.FromNodeCode);

                    if (!string.IsNullOrWhiteSpace(segment.EdgeCode))
                    {
                        edgeCodesToRelease.Add(segment.EdgeCode);
                    }

                    if (string.Equals(segment.ToNodeCode, lastNodeId, StringComparison.OrdinalIgnoreCase))
                    {
                        matchedLastNode = true;
                        break;
                    }

                    nodeCodesToRelease.Add(segment.ToNodeCode);
                }

                if (!matchedLastNode || (nodeCodesToRelease.Count == 0 && edgeCodesToRelease.Count == 0))
                {
                    return;
                }

                var releasedCount = await _unifiedTrafficControlService.ReleasePathLocksAsync(
                    activeCache.MapCode,
                    nodeCodesToRelease,
                    edgeCodesToRelease,
                    robotId);

                if (releasedCount > 0)
                {
                    _logger.LogDebug(
                        "[路径锁] 已按LastNode释放执行过锁: RobotId={RobotId}, LastNode={LastNode}, ReleasedCount={Count}",
                        robotId, lastNodeId, releasedCount);
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex,
                    "[路径锁] 按LastNode释放执行过锁失败: RobotId={RobotId}, LastNode={LastNode}",
                    robotId, lastNodeId);
            }
        }

        /// <summary>
        /// 处理NewBaseRequest请求,当车辆快到当前段终点时,调用任务服务发送下一段路径指令
        /// @author zzy
        /// </summary>
        /// <param name="robotManufacturer">机器人制造商</param>
        /// <param name="robotSerialNumber">机器人序列号</param>
        private async Task HandleNewBaseRequestAsync(string robotManufacturer, string robotSerialNumber)
        {
            try
            {
                // 使用Scope解析协议服务,避免循环依赖
                using var scope = _scopeFactory.CreateScope();
                var protocolServiceFactory = scope.ServiceProvider.GetRequiredService<IProtocolServiceFactory>();
                var protocol = protocolServiceFactory.GetService(ProtocolType.VDA);

                // 判断是否所有段都已发送完毕,若是则跳过发送
                // @author zzy
                var allSent = await protocol.IsAllSegmentsSentAsync(robotManufacturer, robotSerialNumber);
                if (allSent)
                {
                    return;
                }

                // 判断机器人当前是否行驶在目前已下发路径集合中的最后一段路径上
                // 若不在最后一段上,则跳过发送(避免在已下发路径中间段时重复请求)
                // @author zzy
                var onLastSentSegment = await protocol.IsOnLastSentSegmentAsync(robotManufacturer, robotSerialNumber);
                if (!onLastSentSegment)
                {
                    return;
                }

                // 调用任务服务发送下一段路径指令
                await protocol.SendNextSegmentAsync(robotManufacturer, robotSerialNumber);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理NewBaseRequest失败: Robot={Manufacturer}:{SerialNumber}",
                    robotManufacturer, robotSerialNumber);
            }
        }

        /// <summary>
        /// 判断机器人是否存在执行中的主任务,且该主任务包含执行中的子任务
        /// @author zzy
        /// </summary>
        /// <param name="robotManufacturer">机器人制造商</param>
        /// <param name="robotSerialNumber">机器人序列号</param>
        /// <returns>存在则返回true,否则返回false</returns>
        private async Task<bool> HasInProgressTaskWithInProgressSubTaskAsync(
            string robotManufacturer,
            string robotSerialNumber)
        {
            var basicInfo = await _robotCacheService.GetBasicAsync(robotManufacturer, robotSerialNumber);
            if (basicInfo == null || !Guid.TryParse(basicInfo.RobotId, out var robotId))
            {
                return false;
            }

            using var scope = _scopeFactory.CreateScope();
            var taskRepository = scope.ServiceProvider.GetRequiredService<IRobotTaskRepository>();
            var robotTasks = await taskRepository.GetByRobotIdAsync(robotId);

            return robotTasks.Any(task =>
                task.Status == Rcs.Domain.Entities.TaskStatus.InProgress
                && task.SubTasks.Any(subTask => subTask.Status == Rcs.Domain.Entities.TaskStatus.InProgress));
        }

        /// <summary>
        /// 尝试处理VDA5050订单完成判断
        /// 从State消息中提取关键字段,委托给协议服务进行完成判断
        /// 失败不影响正常的State消息处理流程
        /// @author zzy
        /// </summary>
        /// <param name="robotManufacturer">机器人制造商</param>
        /// <param name="robotSerialNumber">机器人序列号</param>
        /// <param name="stateInfo">VDA5050 State消息数据</param>
        private async Task TryHandleOrderCompletionAsync(
            string robotManufacturer,
            string robotSerialNumber,
            State stateInfo)
        {
            try
            {
                using var scope = _scopeFactory.CreateScope();
                var protocolServiceFactory = scope.ServiceProvider.GetRequiredService<IProtocolServiceFactory>();
                var protocol = protocolServiceFactory.GetService(ProtocolType.VDA);

                var completed = await protocol.TryCompleteOrderFromStateAsync(
                    robotManufacturer,
                    robotSerialNumber,
                    stateInfo);

                if (completed)
                {
                    _logger.LogInformation(
                        "[VDA完成] 自动检测到订单完成: Robot={Manufacturer}:{SerialNumber}, OrderId={OrderId}",
                        robotManufacturer, robotSerialNumber, stateInfo.OrderId);
                }
            }
            catch (Exception ex)
            {
                // 完成判断失败不应影响正常的State消息处理流程
                _logger.LogError(ex,
                    "[VDA完成] 订单完成判断异常: Robot={Manufacturer}:{SerialNumber}, OrderId={OrderId}",
                    robotManufacturer, robotSerialNumber, stateInfo.OrderId);
            }
        }
    }
}