JunctionConflictResolver.cs 20.3 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
using Microsoft.Extensions.Logging;
using Rcs.Application.Services;
using Rcs.Application.Services.PathFind;
using Rcs.Application.Services.PathFind.Models;
using StackExchange.Redis;
using System.Text.Json;

namespace Rcs.Infrastructure.PathFinding.Services;

/// <summary>
/// 路口冲突解决器 - 实现智能避让决策
/// @author zzy
/// @date 2026-03-10
/// </summary>
public class JunctionConflictResolver
{
    private readonly IUnifiedTrafficControlService _trafficControl;
    private readonly IRobotCacheService _robotCache;
    private readonly IAgvPathService _pathService;
    private readonly IConnectionMultiplexer _redis;
    private readonly ILogger<JunctionConflictResolver> _logger;

    // Redis Key前缀
    private const string JunctionWaitKeyPrefix = "rcs:junction:wait:";
    private const string RobotPriorityKeyPrefix = "rcs:robot:priority:";

    // 配置参数
    private readonly JunctionConflictSettings _settings = new()
    {
        ShortWaitThresholdSeconds = 5,
        MediumWaitThresholdSeconds = 15,
        LongWaitThresholdSeconds = 30,
        DetectionRadiusMeters = 50.0,
        PreemptiveTriggerSeconds = 10,
        EnableLateralAvoidance = true,
        EnablePreemptiveAvoidance = true,
        EnableParkingAvoidance = true
    };

    public JunctionConflictResolver(
        IUnifiedTrafficControlService trafficControl,
        IRobotCacheService robotCache,
        IAgvPathService pathService,
        IConnectionMultiplexer redis,
        ILogger<JunctionConflictResolver> logger)
    {
        _trafficControl = trafficControl;
        _robotCache = robotCache;
        _pathService = pathService;
        _redis = redis;
        _logger = logger;
    }

    /// <summary>
    /// 解决路口冲突 - 核心决策方法
    /// @author zzy
    /// </summary>
    public async Task<ConflictResolutionResult> ResolveJunctionConflictAsync(
        Guid robotId,
        string mapCode,
        string junctionNodeCode,
        List<PathSegment> nextSegments,
        PathGraph graph)
    {
        try
        {
            // 1. 获取路口信息
            var junctionInfo = GetJunctionInfo(junctionNodeCode, graph);
            if (junctionInfo == null)
            {
                return ConflictResolutionResult.NoConflict();
            }

            // 2. 检测路口冲突
            var conflictInfo = await DetectJunctionConflictAsync(
                robotId, mapCode, junctionNodeCode, junctionInfo);

            if (!conflictInfo.HasConflict)
            {
                return ConflictResolutionResult.NoConflict();
            }

            // 3. 获取我的优先级信息
            var myPriority = await GetRobotPriorityInfoAsync(robotId);

            // 4. 比较优先级,判断是否需要避让
            var shouldYield = await ShouldYieldAsync(myPriority, conflictInfo.ConflictingRobots);

            if (!shouldYield)
            {
                // 优先级高,不需要避让,继续等待锁释放
                return ConflictResolutionResult.NoConflict();
            }

            // 5. 获取等待时长
            var waitDuration = await GetWaitDurationAsync(robotId, junctionNodeCode);

            // 6. 根据等待时长和路口类型选择避让策略
            var strategy = SelectAvoidanceStrategy(
                waitDuration, junctionInfo, conflictInfo);

            // 7. 根据策略查找避让位置
            var avoidanceNodeCode = await FindAvoidanceLocationAsync(
                robotId, mapCode, junctionNodeCode, strategy, junctionInfo, graph);

            return new ConflictResolutionResult
            {
                ShouldAvoid = true,
                Strategy = strategy,
                JunctionNodeCode = junctionNodeCode,
                AvoidanceNodeCode = avoidanceNodeCode,
                OriginalTargetNodeCode = nextSegments.FirstOrDefault()?.ToNodeId.ToString(),
                Reason = $"优先级较低,等待{waitDuration.TotalSeconds:F1}秒,采用{strategy}策略"
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "路口冲突解决异常: RobotId={RobotId}, Junction={Junction}",
                robotId, junctionNodeCode);
            return ConflictResolutionResult.NoConflict();
        }
    }

    /// <summary>
    /// 获取路口信息
    /// @author zzy
    /// </summary>
    private JunctionInfo? GetJunctionInfo(string junctionNodeCode, PathGraph graph)
    {
        var node = graph.Nodes.Values.FirstOrDefault(n => n.NodeCode == junctionNodeCode);
        if (node == null || node.OutEdges.Count < 3)
        {
            return null;
        }

        var connectedNodes = node.OutEdges
            .Select(e => graph.Nodes.TryGetValue(e.ToNodeId, out var n) ? n.NodeCode : string.Empty)
            .Where(code => !string.IsNullOrEmpty(code))
            .ToList();

        // 识别可用于避让的岔路(非主干道节点)
        var avoidanceLanes = connectedNodes
            .Where(code => IsAvoidanceLane(code, graph))
            .ToList();

        // 识别临时停靠点(标记为停靠点的节点)
        var parkingSpots = connectedNodes
            .Where(code => IsParkingSpot(code, graph))
            .ToList();

        return new JunctionInfo
        {
            JunctionNodeCode = junctionNodeCode,
            Type = DetermineJunctionType(connectedNodes.Count),
            ConnectedNodeCodes = connectedNodes,
            AvoidanceLaneNodeCodes = avoidanceLanes,
            ParkingSpotNodeCodes = parkingSpots,
            JunctionRadius = 10.0
        };
    }

    /// <summary>
    /// 检测路口冲突
    /// @author zzy
    /// </summary>
    private async Task<JunctionConflictInfo> DetectJunctionConflictAsync(
        Guid robotId,
        string mapCode,
        string junctionNodeCode,
        JunctionInfo junctionInfo)
    {
        var conflictInfo = new JunctionConflictInfo
        {
            HasConflict = false,
            ConflictingRobots = new List<RobotPriorityInfo>()
        };

        // 检查路口节点是否被其他机器人占用
        var junctionOccupied = await _trafficControl.IsNodeOccupiedByOtherAsync(
            mapCode, junctionNodeCode, robotId);

        if (junctionOccupied)
        {
            conflictInfo.HasConflict = true;
            // 获取占用路口的机器人信息
            var occupyingRobots = await GetRobotsOccupyingJunctionAsync(
                mapCode, junctionNodeCode, robotId);
            conflictInfo.ConflictingRobots.AddRange(occupyingRobots);
        }

        // 检查连接路口的边是否存在逆向冲突
        foreach (var connectedNode in junctionInfo.ConnectedNodeCodes)
        {
            var edgeCode = GetEdgeCode(junctionNodeCode, connectedNode, null);
            if (string.IsNullOrEmpty(edgeCode)) continue;

            var hasReverseConflict = await _trafficControl.HasReverseConflictAsync(
                mapCode, edgeCode, junctionNodeCode, connectedNode, robotId);

            if (hasReverseConflict)
            {
                conflictInfo.HasConflict = true;
                conflictInfo.HasReverseConflict = true;
                break;
            }
        }

        return conflictInfo;
    }

    /// <summary>
    /// 获取机器人优先级信息
    /// @author zzy
    /// </summary>
    private async Task<RobotPriorityInfo> GetRobotPriorityInfoAsync(Guid robotId)
    {
        var db = _redis.GetDatabase();
        var key = $"{RobotPriorityKeyPrefix}{robotId}";
        var json = await db.StringGetAsync(key);

        if (!json.IsNullOrEmpty)
        {
            var cached = JsonSerializer.Deserialize<RobotPriorityInfo>(json.ToString());
            if (cached != null)
                return cached;
        }

        // 从缓存服务获取机器人信息
        var robotCaches = await _robotCache.GetAllActiveRobotCacheAsync();
        var robotCache = robotCaches.FirstOrDefault(item =>
            Guid.TryParse(item.Basic.RobotId, out var cacheRobotId) && cacheRobotId == robotId);
        var status = robotCache.Status;

        var priorityInfo = new RobotPriorityInfo
        {
            RobotId = robotId,
            Priority = 50, // 默认优先级
            IsLoaded = false,
            BatteryLevel = status?.BatteryLevel ?? 100,
            ArrivalTime = DateTime.Now
        };

        // 缓存5秒
        await db.StringSetAsync(key, JsonSerializer.Serialize(priorityInfo), TimeSpan.FromSeconds(5));

        return priorityInfo;
    }

    /// <summary>
    /// 判断是否应该让行
    /// @author zzy
    /// </summary>
    private async Task<bool> ShouldYieldAsync(
        RobotPriorityInfo myInfo,
        List<RobotPriorityInfo> conflictingRobots)
    {
        if (!conflictingRobots.Any())
            return false;

        var comparer = new RobotPriorityComparer();

        // 如果存在任何一个优先级比我高的机器人,我就需要让行
        foreach (var other in conflictingRobots)
        {
            if (comparer.Compare(myInfo, other) > 0)
            {
                return true; // 对方优先级更高,我需要让行
            }
        }

        return false;
    }

    /// <summary>
    /// 选择避让策略
    /// @author zzy
    /// </summary>
    private AvoidanceStrategy SelectAvoidanceStrategy(
        TimeSpan waitDuration,
        JunctionInfo junctionInfo,
        JunctionConflictInfo conflictInfo)
    {
        // 等待时间短(<5秒),原地等待
        if (waitDuration.TotalSeconds < _settings.ShortWaitThresholdSeconds)
        {
            return AvoidanceStrategy.Wait;
        }

        // 等待时间中等(5-15秒),尝试侧向避让
        if (waitDuration.TotalSeconds < _settings.MediumWaitThresholdSeconds)
        {
            if (_settings.EnableLateralAvoidance && junctionInfo.AvoidanceLaneNodeCodes.Any())
            {
                return AvoidanceStrategy.Lateral;
            }

            if (_settings.EnableParkingAvoidance && junctionInfo.ParkingSpotNodeCodes.Any())
            {
                return AvoidanceStrategy.Parking;
            }

            return AvoidanceStrategy.Wait;
        }

        // 等待时间长(15-30秒),尝试停靠或后退
        if (waitDuration.TotalSeconds < _settings.LongWaitThresholdSeconds)
        {
            if (_settings.EnableParkingAvoidance && junctionInfo.ParkingSpotNodeCodes.Any())
            {
                return AvoidanceStrategy.Parking;
            }

            return AvoidanceStrategy.Retreat;
        }

        // 等待超时(>30秒),重新规划
        return AvoidanceStrategy.Reroute;
    }

    /// <summary>
    /// 查找避让位置
    /// @author zzy
    /// </summary>
    private async Task<string?> FindAvoidanceLocationAsync(
        Guid robotId,
        string mapCode,
        string junctionNodeCode,
        AvoidanceStrategy strategy,
        JunctionInfo junctionInfo,
        PathGraph graph)
    {
        switch (strategy)
        {
            case AvoidanceStrategy.Lateral:
                return await FindAvailableLateralLaneAsync(
                    robotId, mapCode, junctionInfo.AvoidanceLaneNodeCodes);

            case AvoidanceStrategy.Parking:
                return await FindAvailableParkingSpotAsync(
                    robotId, mapCode, junctionInfo.ParkingSpotNodeCodes);

            case AvoidanceStrategy.Retreat:
                return await FindSafeRetreatNodeAsync(
                    robotId, mapCode, junctionNodeCode, graph);

            default:
                return null;
        }
    }

    /// <summary>
    /// 查找可用的侧向岔路
    /// @author zzy
    /// </summary>
    private async Task<string?> FindAvailableLateralLaneAsync(
        Guid robotId,
        string mapCode,
        List<string> laneNodeCodes)
    {
        foreach (var laneNode in laneNodeCodes)
        {
            var isOccupied = await _trafficControl.IsNodeOccupiedByOtherAsync(
                mapCode, laneNode, robotId);

            if (!isOccupied)
            {
                return laneNode;
            }
        }

        return null;
    }

    /// <summary>
    /// 查找可用的停靠点
    /// @author zzy
    /// </summary>
    private async Task<string?> FindAvailableParkingSpotAsync(
        Guid robotId,
        string mapCode,
        List<string> parkingSpotCodes)
    {
        foreach (var spotNode in parkingSpotCodes)
        {
            var isOccupied = await _trafficControl.IsNodeOccupiedByOtherAsync(
                mapCode, spotNode, robotId);

            if (!isOccupied)
            {
                return spotNode;
            }
        }

        return null;
    }

    /// <summary>
    /// 查找安全后退节点
    /// @author zzy
    /// </summary>
    private async Task<string?> FindSafeRetreatNodeAsync(
        Guid robotId,
        string mapCode,
        string junctionNodeCode,
        PathGraph graph)
    {
        var junctionNode = graph.Nodes.Values.FirstOrDefault(n => n.NodeCode == junctionNodeCode);
        if (junctionNode == null)
            return null;

        // 查找入边的起点节点(上一个节点)
        foreach (var inEdge in junctionNode.InEdges)
        {
            if (graph.Nodes.TryGetValue(inEdge.FromNodeId, out var fromNode))
            {
                // 检查该节点是否为安全节点(非路口)
                if (fromNode.OutEdges.Count < 3)
                {
                    var isOccupied = await _trafficControl.IsNodeOccupiedByOtherAsync(
                        mapCode, fromNode.NodeCode, robotId);

                    if (!isOccupied)
                    {
                        return fromNode.NodeCode;
                    }
                }
            }
        }

        return null;
    }

    #region 辅助方法

    /// <summary>
    /// 获取等待时长
    /// @author zzy
    /// </summary>
    private async Task<TimeSpan> GetWaitDurationAsync(Guid robotId, string junctionNodeCode)
    {
        var db = _redis.GetDatabase();
        var key = $"{JunctionWaitKeyPrefix}{junctionNodeCode}:{robotId}";
        var startTimeStr = await db.StringGetAsync(key);

        if (startTimeStr.IsNullOrEmpty)
        {
            // 首次等待,记录开始时间
            await db.StringSetAsync(key, DateTime.Now.Ticks.ToString(), TimeSpan.FromMinutes(2));
            return TimeSpan.Zero;
        }

        if (long.TryParse(startTimeStr.ToString(), out var ticks))
        {
            var startTime = new DateTime(ticks);
            return DateTime.Now - startTime;
        }

        return TimeSpan.Zero;
    }

    /// <summary>
    /// 获取占用路口的机器人列表
    /// @author zzy
    /// </summary>
    private async Task<List<RobotPriorityInfo>> GetRobotsOccupyingJunctionAsync(
        string mapCode,
        string junctionNodeCode,
        Guid excludeRobotId)
    {
        var robotIds = await _trafficControl.GetRobotsOccupyingNodeAsync(mapCode, junctionNodeCode);
        var filtered = robotIds
            .Where(id => id != excludeRobotId)
            .Distinct()
            .ToList();

        if (filtered.Count == 0)
        {
            return new List<RobotPriorityInfo>();
        }

        var result = new List<RobotPriorityInfo>();
        foreach (var robotId in filtered)
        {
            var info = await GetRobotPriorityInfoAsync(robotId);
            result.Add(info);
        }

        return result;
    }

    /// <summary>
    /// 判断节点是否为避让岔路
    /// @author zzy
    /// </summary>
    private bool IsAvoidanceLane(string nodeCode, PathGraph graph)
    {
        var node = graph.Nodes.Values.FirstOrDefault(n => n.NodeCode == nodeCode);
        if (node == null) return false;

        // 简化判断:出度<=2的节点可作为避让岔路
        return node.OutEdges.Count <= 2;
    }

    /// <summary>
    /// 判断节点是否为停靠点
    /// @author zzy
    /// </summary>
    private bool IsParkingSpot(string nodeCode, PathGraph graph)
    {
        // 简化实现:节点名称包含"parking"或"wait"的视为停靠点
        return nodeCode.Contains("parking", StringComparison.OrdinalIgnoreCase) ||
               nodeCode.Contains("wait", StringComparison.OrdinalIgnoreCase);
    }

    /// <summary>
    /// 确定路口类型
    /// @author zzy
    /// </summary>
    private JunctionType DetermineJunctionType(int connectedCount)
    {
        return connectedCount switch
        {
            2 => JunctionType.TwoWay,
            3 => JunctionType.ThreeWay,
            4 => JunctionType.FourWay,
            _ => JunctionType.MultiWay
        };
    }

    /// <summary>
    /// 获取边编码
    /// @author zzy
    /// </summary>
    private string GetEdgeCode(string fromNodeCode, string toNodeCode, PathGraph? graph)
    {
        // 简化实现:使用节点编码组合
        return $"{fromNodeCode}-{toNodeCode}";
    }

    #endregion
}

#region 数据模型

/// <summary>
/// 路口信息
/// @author zzy
/// </summary>
public class JunctionInfo
{
    public string JunctionNodeCode { get; set; } = string.Empty;
    public JunctionType Type { get; set; }
    public List<string> ConnectedNodeCodes { get; set; } = new();
    public List<string> AvoidanceLaneNodeCodes { get; set; } = new();
    public List<string> ParkingSpotNodeCodes { get; set; } = new();
    public double JunctionRadius { get; set; }
}

/// <summary>
/// 路口类型
/// @author zzy
/// </summary>
public enum JunctionType
{
    TwoWay = 2,
    ThreeWay = 3,
    FourWay = 4,
    MultiWay = 5
}

/// <summary>
/// 路口冲突信息
/// @author zzy
/// </summary>
public class JunctionConflictInfo
{
    public bool HasConflict { get; set; }
    public bool HasReverseConflict { get; set; }
    public List<RobotPriorityInfo> ConflictingRobots { get; set; } = new();
}

/// <summary>
/// 机器人优先级信息
/// @author zzy
/// </summary>
public class RobotPriorityInfo
{
    public Guid RobotId { get; set; }
    public int Priority { get; set; }
    public bool IsLoaded { get; set; }
    public int BatteryLevel { get; set; }
    public DateTime ArrivalTime { get; set; }
}

/// <summary>
/// 机器人优先级比较器
/// @author zzy
/// </summary>
public class RobotPriorityComparer
{
    /// <summary>
    /// 比较两个机器人的优先级
    /// 返回值:-1表示robot1优先级高,1表示robot2优先级高,0表示相同
    /// @author zzy
    /// </summary>
    public int Compare(RobotPriorityInfo robot1, RobotPriorityInfo robot2)
    {
        // 1. 任务优先级(数值越小优先级越高)
        if (robot1.Priority != robot2.Priority)
            return robot1.Priority.CompareTo(robot2.Priority);

        // 2. 载货状态(载货优先)
        if (robot1.IsLoaded != robot2.IsLoaded)
            return robot2.IsLoaded.CompareTo(robot1.IsLoaded);

        // 3. 电池电量(低电量优先)
        if (Math.Abs(robot1.BatteryLevel - robot2.BatteryLevel) > 5)
            return robot1.BatteryLevel.CompareTo(robot2.BatteryLevel);

        // 4. 到达时间(先到先行)
        if (robot1.ArrivalTime != robot2.ArrivalTime)
            return robot1.ArrivalTime.CompareTo(robot2.ArrivalTime);

        // 5. 机器人ID(兜底,保证确定性)
        return robot1.RobotId.CompareTo(robot2.RobotId);
    }
}

/// <summary>
/// 冲突解决结果
/// @author zzy
/// </summary>
public class ConflictResolutionResult
{
    public bool ShouldAvoid { get; set; }
    public AvoidanceStrategy Strategy { get; set; }
    public string JunctionNodeCode { get; set; } = string.Empty;
    public string? AvoidanceNodeCode { get; set; }
    public string? OriginalTargetNodeCode { get; set; }
    public string Reason { get; set; } = string.Empty;

    public static ConflictResolutionResult NoConflict() => new()
    {
        ShouldAvoid = false,
        Strategy = AvoidanceStrategy.None,
        Reason = "无冲突"
    };
}

/// <summary>
/// 路口冲突配置
/// @author zzy
/// </summary>
public class JunctionConflictSettings
{
    public int ShortWaitThresholdSeconds { get; set; } = 5;
    public int MediumWaitThresholdSeconds { get; set; } = 15;
    public int LongWaitThresholdSeconds { get; set; } = 30;
    public double DetectionRadiusMeters { get; set; } = 50.0;
    public int PreemptiveTriggerSeconds { get; set; } = 10;
    public bool EnableLateralAvoidance { get; set; } = true;
    public bool EnablePreemptiveAvoidance { get; set; } = true;
    public bool EnableParkingAvoidance { get; set; } = true;
}

#endregion