GlobalNavigationCoordinator.cs
77.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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Channels;
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.PathFind.Realtime;
using Rcs.Domain.Entities;
using Rcs.Domain.Enums;
using Rcs.Domain.Settings;
using StackExchange.Redis;
namespace Rcs.Infrastructure.PathFinding.Realtime;
/// <summary>
/// 全局导航实时协调器,基于状态事件和冲突事件在发送前给出路径调整决策。
/// </summary>
public sealed class GlobalNavigationCoordinator : BackgroundService, IGlobalNavigationCoordinator
{
/// <summary>
/// 路口队列相关 Redis Key 前缀。
/// </summary>
private const string QueueKeyPrefix = "rcs:route:queue";
/// <summary>
/// 正常发送模式编码。
/// </summary>
private const string ModeNormal = RouteModeCodes.Normal;
/// <summary>
/// 等待模式编码。
/// </summary>
private const string ModeHold = RouteModeCodes.HoldingAtWaitNode;
/// <summary>
/// 排队模式编码。
/// </summary>
private const string ModeQueue = RouteModeCodes.QueueingForJunction;
/// <summary>
/// 占用路口模式编码。
/// </summary>
private const string ModeOccupying = RouteModeCodes.OccupyingJunction;
/// <summary>
/// 绕行模式编码。
/// </summary>
private const string ModeDetouring = RouteModeCodes.Detouring;
/// <summary>
/// 重规划待执行模式编码。
/// </summary>
private const string ModeReplanPending = RouteModeCodes.ReplanPending;
/// <summary>
/// 阻塞保护模式编码。
/// </summary>
private const string ModeBlocked = RouteModeCodes.Blocked;
/// <summary>
/// 继续发送策略编码。
/// </summary>
private const string StrategyContinue = "Continue";
/// <summary>
/// 头段裁剪对齐策略编码。
/// </summary>
private const string StrategyTrim = "TrimProgressAlign";
/// <summary>
/// 就近等待策略编码。
/// </summary>
private const string StrategyWait = "WaitNearest";
/// <summary>
/// 路口排队占位策略编码。
/// </summary>
private const string StrategyQueue = "JunctionOccupy";
/// <summary>
/// 局部绕行策略编码。
/// </summary>
private const string StrategyDetour = "LocalDetour";
/// <summary>
/// 侧向让行策略编码。
/// </summary>
private const string StrategyLateral = "LateralYield";
/// <summary>
/// 泊车让行策略编码。
/// </summary>
private const string StrategyParking = "ParkingYield";
/// <summary>
/// 退让策略编码。
/// </summary>
private const string StrategyRetreat = "Retreat";
/// <summary>
/// 尾段重规划策略编码。
/// </summary>
private const string StrategyReplan = "ReplanTail";
/// <summary>
/// 阻塞保护策略编码。
/// </summary>
private const string StrategyBlocked = "Blocked";
/// <summary>
/// 运行日志。
/// </summary>
private readonly ILogger<GlobalNavigationCoordinator> _logger;
/// <summary>
/// 路口与资源占用控制服务。
/// </summary>
private readonly IUnifiedTrafficControlService _trafficControl;
/// <summary>
/// 路径服务。
/// </summary>
private readonly IAgvPathService _agvPathService;
/// <summary>
/// 避让策略选择器。
/// </summary>
private readonly IAvoidanceStrategySelector _strategySelector;
/// <summary>
/// Redis 连接。
/// </summary>
private readonly IConnectionMultiplexer _redis;
/// <summary>
/// 配置变更订阅句柄。
/// </summary>
private readonly IDisposable? _settingsChangeSubscription;
/// <summary>
/// 协调器配置快照。
/// </summary>
private GlobalCoordinatorSettings _coordinatorSettings = new();
/// <summary>
/// 机器人状态事件通道。
/// </summary>
private readonly Channel<RobotStateNavigationEvent> _stateEvents;
/// <summary>
/// 机器人运行态快照。
/// </summary>
private readonly ConcurrentDictionary<Guid, RobotNavSnapshot> _robotSnapshots = new();
/// <summary>
/// 锁冲突快照。
/// </summary>
private readonly ConcurrentDictionary<Guid, LockConflictSnapshot> _lockConflictSnapshots = new();
/// <summary>
/// 策略命中次数统计。
/// </summary>
private readonly ConcurrentDictionary<string, long> _decisionStrategyCounts = new(StringComparer.Ordinal);
/// <summary>
/// 继续决策计数。
/// </summary>
private long _decisionContinueCount;
/// <summary>
/// 等待决策计数。
/// </summary>
private long _decisionHoldCount;
/// <summary>
/// 补丁决策计数。
/// </summary>
private long _decisionPatchCount;
/// <summary>
/// 最近一次指标日志时间。
/// </summary>
private DateTime _lastDecisionMetricsLogUtc = DateTime.Now;
/// <summary>
/// 指标日志间隔。
/// </summary>
private TimeSpan _decisionMetricsLogInterval = TimeSpan.FromSeconds(60);
public GlobalNavigationCoordinator(
ILogger<GlobalNavigationCoordinator> logger,
IUnifiedTrafficControlService trafficControl,
IAgvPathService agvPathService,
IAvoidanceStrategySelector strategySelector,
IConnectionMultiplexer redis,
IOptionsMonitor<AppSettings> settings)
{
_logger = logger;
_trafficControl = trafficControl;
_agvPathService = agvPathService;
_strategySelector = strategySelector;
_redis = redis;
ApplyCoordinatorSettings(settings.CurrentValue);
_settingsChangeSubscription = settings.OnChange(ApplyCoordinatorSettings);
_stateEvents = Channel.CreateUnbounded<RobotStateNavigationEvent>(new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = false
});
}
/// <summary>
/// 将机器人实时状态写入内部通道,采用事件解耦原则降低发送链路与决策链路耦合度。
/// </summary>
public Task PublishStateEventAsync(RobotStateNavigationEvent evt, CancellationToken ct = default)
{
if (!_stateEvents.Writer.TryWrite(evt))
{
_logger.LogDebug("[全局导航] 丢弃状态事件: RobotId={RobotId}", evt.RobotId);
}
return Task.CompletedTask;
}
/// <summary>
/// 接收并聚合锁冲突事件,通过时间连续性累计冲突强度,为策略升级提供事实依据。
/// </summary>
public Task PublishLockConflictEventAsync(LockConflictNavigationEvent evt, CancellationToken ct = default)
{
if (evt.RobotId == Guid.Empty)
{
return Task.CompletedTask;
}
var occurredAtUtc = evt.OccurredAtUtc == default ? DateTime.Now : evt.OccurredAtUtc;
_lockConflictSnapshots.AddOrUpdate(
evt.RobotId,
_ => new LockConflictSnapshot
{
MapCode = evt.MapCode,
LastNodeCode = evt.NodeCode,
LastEdgeCode = evt.EdgeCode,
LastFailureReason = evt.FailureReason,
LastOccurredAtUtc = occurredAtUtc,
ReverseConflictStreak = evt.HasReverseConflict ? 1 : 0,
TotalConflictStreak = 1
},
(_, old) =>
{
var contiguous = occurredAtUtc - old.LastOccurredAtUtc <= TimeSpan.FromSeconds(10);
return new LockConflictSnapshot
{
MapCode = string.IsNullOrWhiteSpace(evt.MapCode) ? old.MapCode : evt.MapCode,
LastNodeCode = evt.NodeCode,
LastEdgeCode = evt.EdgeCode,
LastFailureReason = evt.FailureReason,
LastOccurredAtUtc = occurredAtUtc,
ReverseConflictStreak = evt.HasReverseConflict
? (contiguous ? old.ReverseConflictStreak + 1 : 1)
: 0,
TotalConflictStreak = contiguous ? old.TotalConflictStreak + 1 : 1
};
});
return Task.CompletedTask;
}
/// <summary>
/// 应用热更新配置并刷新阈值参数,保证策略可在线调参与即时生效。
/// </summary>
private void ApplyCoordinatorSettings(AppSettings appSettings)
{
var next = appSettings.GlobalNavigation?.Coordinator ?? new GlobalCoordinatorSettings();
_coordinatorSettings = next;
_decisionMetricsLogInterval = TimeSpan.FromSeconds(Math.Max(10, next.DecisionMetricsIntervalSeconds));
_logger.LogInformation(
"[全局导航] 配置已更新: 恢复稳定阈值={ResumeStable}, 短等待秒数={HoldShort}, 排队等待秒数={HoldQueue}, 排队过期秒数={QueueStale}, 升级-等待阈值={EscalateWait}, 升级-绕行阈值={EscalateDetour}, 升级-侧向避让阈值={EscalateLateral}, 升级-泊车避让阈值={EscalateParking}, 升级-后退阈值={EscalateRetreat}, 升级-重规划阈值={EscalateReplan}, 升级-阻塞阈值={EscalateBlocked}, 阻塞等待秒数={BlockedHold}, 启用侧向避让={EnableLateral}, 启用泊车避让={EnableParking}, 启用后退={EnableRetreat}",
next.ResumeStablePassThreshold,
next.HoldSecondsShort,
next.HoldSecondsQueue,
next.QueueStaleSeconds,
next.ConflictEscalateNearestWaitThreshold,
next.ConflictEscalateDetourThreshold,
next.ConflictEscalateLateralYieldThreshold,
next.ConflictEscalateParkingThreshold,
next.ConflictEscalateRetreatThreshold,
next.ConflictEscalateReplanThreshold,
next.ConflictEscalateBlockedThreshold,
next.BlockedHoldSeconds,
next.EnableLateralYield,
next.EnableParkingYield,
next.EnableRetreat);
}
/// <summary>
/// 发送前主决策入口,基于状态机与冲突探测结果在继续、等待、补丁与重规划间做选择。
/// </summary>
public async Task<RouteAdjustmentDecision> TryAdjustBeforeSendAsync(
Guid robotId,
VdaSegmentedPathCache cache,
string? lastNodeCode,
bool isDriving,
CancellationToken ct = default)
{
if (cache.CurrentJunctionIndex >= cache.JunctionSegments.Count)
{
return Continue("all segments sent");
}
var (lastNode, driving) = ResolveRuntime(robotId, lastNodeCode, isDriving);
var first = GetFirstUnsentSegment(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex);
if (first == null)
{
return Continue("unsent empty");
}
if (!string.Equals(cache.RouteMode, ModeQueue, StringComparison.Ordinal) &&
!string.Equals(cache.RouteMode, ModeOccupying, StringComparison.Ordinal) &&
!string.IsNullOrWhiteSpace(cache.HoldNodeCode))
{
await ReleaseQueueTicketAsync(robotId, cache.MapCode, cache.HoldNodeCode);
}
if (string.Equals(cache.RouteMode, ModeHold, StringComparison.Ordinal))
{
return await HandleHoldAsync(robotId, cache, first, lastNode, driving, ct);
}
if (string.Equals(cache.RouteMode, ModeQueue, StringComparison.Ordinal))
{
return await HandleQueueAsync(robotId, cache, first, lastNode, driving, ct);
}
if (string.Equals(cache.RouteMode, ModeOccupying, StringComparison.Ordinal))
{
return await HandleOccupyingAsync(robotId, cache, first, lastNode, driving, ct);
}
if (string.Equals(cache.RouteMode, ModeReplanPending, StringComparison.Ordinal))
{
return await HandleReplanPendingAsync(robotId, cache, first, lastNode, driving, ct);
}
if (string.Equals(cache.RouteMode, ModeBlocked, StringComparison.Ordinal))
{
return await HandleBlockedAsync(robotId, cache, first, lastNode, driving, ct);
}
var trim = TryBuildTrimHeadPatch(cache, lastNode);
if (trim != null)
{
cache.LastDecisionCode = StrategyTrim;
return Patch(trim, "trim stale head");
}
var conflict = await ProbeConflictAsync(robotId, cache.MapCode, first);
if (!conflict.HasConflict)
{
cache.RouteMode = ModeNormal;
cache.StablePassCount = Math.Max(cache.StablePassCount + 1, 1);
cache.ConsecutiveConflictFailCount = 0;
cache.BlockedReason = null;
_lockConflictSnapshots.TryRemove(robotId, out _);
return Continue("normal");
}
if (conflict.HasReverseConflict)
{
var (queuePos, queueSize) = await EnsureQueueTicketAsync(robotId, cache.MapCode, first.FromNodeCode, ct);
if (queuePos <= 0)
{
return Hold(
cache,
StrategyQueue,
Math.Max(1, _coordinatorSettings.HoldSecondsQueue),
first.FromNodeCode,
$"occupy granted and waiting release (1/{queueSize})",
ModeOccupying);
}
return Hold(
cache,
StrategyQueue,
Math.Max(1, _coordinatorSettings.HoldSecondsQueue),
first.FromNodeCode,
$"reverse conflict queueing ({queuePos + 1}/{queueSize})");
}
return Hold(cache, StrategyWait, Math.Max(1, _coordinatorSettings.HoldSecondsShort), first.FromNodeCode, "occupied, wait nearest");
}
/// <summary>
/// 处理等待态流程,依据等待窗口、节点一致性与冲突连续性决定续等或升级。
/// </summary>
private async Task<RouteAdjustmentDecision> HandleHoldAsync(
Guid robotId,
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
string? lastNode,
bool driving,
CancellationToken ct)
{
var waitNode = cache.HoldNodeCode ?? first.FromNodeCode;
var atWaitNode = string.Equals(waitNode, lastNode, StringComparison.OrdinalIgnoreCase);
if (!atWaitNode || driving)
{
return Hold(cache, StrategyWait, Math.Max(1, _coordinatorSettings.HoldSecondsShort), waitNode, "waiting robot stop at wait node");
}
var conflict = await ProbeConflictAsync(robotId, cache.MapCode, first);
if (!conflict.HasConflict)
{
cache.StablePassCount = Math.Max(cache.StablePassCount, 0) + 1;
cache.ConsecutiveConflictFailCount = 0;
cache.BlockedReason = null;
if (cache.StablePassCount < Math.Max(1, _coordinatorSettings.ResumeStablePassThreshold))
{
return Hold(cache, StrategyWait, 1, waitNode, "precheck pass not stable");
}
var trim = TryBuildTrimHeadPatch(cache, lastNode);
return trim != null ? Patch(trim, "resume and trim") : Continue("resume from wait");
}
cache.StablePassCount = Math.Min(cache.StablePassCount, 0) - 1;
var failStreak = Math.Abs(Math.Min(cache.StablePassCount, 0));
if (cache.IsWaitingForNetAction)
{
return Hold(
cache,
StrategyWait,
Math.Max(1, _coordinatorSettings.HoldSecondsShort),
waitNode,
"net action pending, tail mutation disabled");
}
cache.ConsecutiveConflictFailCount = Math.Max(0, cache.ConsecutiveConflictFailCount) + 1;
var hasRecentReverseLockConflict = HasRecentReverseConflictSignal(robotId, cache.MapCode);
var selectionContext = new AvoidanceSelectionContext
{
FailStreak = failStreak,
HasReverseConflict = conflict.HasReverseConflict || hasRecentReverseLockConflict,
EscalateWaitThreshold = _coordinatorSettings.ConflictEscalateNearestWaitThreshold,
EscalateDetourThreshold = _coordinatorSettings.ConflictEscalateDetourThreshold,
EscalateLateralYieldThreshold = _coordinatorSettings.ConflictEscalateLateralYieldThreshold,
EscalateParkingThreshold = _coordinatorSettings.ConflictEscalateParkingThreshold,
EscalateRetreatThreshold = _coordinatorSettings.ConflictEscalateRetreatThreshold,
EscalateReplanThreshold = _coordinatorSettings.ConflictEscalateReplanThreshold,
EnableLateralYield = _coordinatorSettings.EnableLateralYield,
EnableParkingYield = _coordinatorSettings.EnableParkingYield,
EnableRetreat = _coordinatorSettings.EnableRetreat
};
var candidates = _strategySelector.SelectHoldCandidates(selectionContext);
if (candidates.Count > 0)
{
_logger.LogDebug(
"[全局导航] 等待升级候选策略: RobotId={RobotId}, FailStreak={FailStreak}, ReverseConflict={ReverseConflict}, Candidates={Candidates}",
robotId,
failStreak,
conflict.HasReverseConflict || hasRecentReverseLockConflict,
string.Join(",", candidates));
}
foreach (var strategy in candidates)
{
var decision = await TryBuildEscalationDecisionAsync(
robotId, cache, first, conflict, lastNode, strategy);
if (decision != null)
{
cache.ConsecutiveConflictFailCount = 0;
return decision;
}
}
if (cache.ConsecutiveConflictFailCount >= Math.Max(1, _coordinatorSettings.ConflictEscalateBlockedThreshold))
{
cache.RouteMode = ModeBlocked;
cache.BlockedReason = "conflict escalated to blocked protection mode";
cache.LastDecisionCode = StrategyBlocked;
var blockedHold = Math.Max(1, _coordinatorSettings.BlockedHoldSeconds);
return Hold(
cache,
StrategyBlocked,
blockedHold,
waitNode,
$"blocked by persistent conflict ({cache.ConsecutiveConflictFailCount})",
ModeBlocked);
}
if (conflict.HasReverseConflict)
{
var (queuePos, queueSize) = await EnsureQueueTicketAsync(robotId, cache.MapCode, waitNode, ct);
if (queuePos <= 0)
{
return Hold(
cache,
StrategyQueue,
Math.Max(1, _coordinatorSettings.HoldSecondsQueue),
waitNode,
$"occupy granted from hold mode (1/{queueSize})",
ModeOccupying);
}
return Hold(
cache,
StrategyQueue,
Math.Max(1, _coordinatorSettings.HoldSecondsQueue),
waitNode,
$"reverse conflict queueing ({queuePos + 1}/{queueSize})");
}
return Hold(cache, StrategyWait, Math.Max(1, _coordinatorSettings.HoldSecondsShort), waitNode, "holding for conflict clear");
}
/// <summary>
/// 处理排队态流程,结合队列位置与占用状态决定继续排队或转入占位执行。
/// </summary>
private async Task<RouteAdjustmentDecision> HandleQueueAsync(
Guid robotId,
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
string? lastNode,
bool driving,
CancellationToken ct)
{
var waitNode = cache.HoldNodeCode ?? first.FromNodeCode;
var (queuePos, queueSize) = await EnsureQueueTicketAsync(robotId, cache.MapCode, waitNode, ct);
if (!string.Equals(waitNode, lastNode, StringComparison.OrdinalIgnoreCase) || driving)
{
return Hold(
cache,
StrategyQueue,
Math.Max(1, _coordinatorSettings.HoldSecondsQueue),
waitNode,
$"queueing and waiting position ({queuePos + 1}/{queueSize})");
}
if (queuePos > 0)
{
cache.StablePassCount = Math.Min(cache.StablePassCount, 0) - 1;
return Hold(
cache,
StrategyQueue,
Math.Max(1, _coordinatorSettings.HoldSecondsQueue),
waitNode,
$"queue turn pending ({queuePos + 1}/{queueSize})");
}
return await HandleOccupyingAsync(
robotId,
cache,
first,
lastNode,
driving,
ct,
queuePos,
queueSize);
}
/// <summary>
/// 处理占位态流程,在已占位前提下等待冲突消退并评估恢复发送时机。
/// </summary>
private async Task<RouteAdjustmentDecision> HandleOccupyingAsync(
Guid robotId,
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
string? lastNode,
bool driving,
CancellationToken ct,
int? knownQueuePos = null,
int? knownQueueSize = null)
{
var waitNode = cache.HoldNodeCode ?? first.FromNodeCode;
var queuePos = knownQueuePos ?? 0;
var queueSize = knownQueueSize ?? 1;
if (!knownQueuePos.HasValue || !knownQueueSize.HasValue)
{
(queuePos, queueSize) = await EnsureQueueTicketAsync(robotId, cache.MapCode, waitNode, ct);
}
if (queuePos > 0)
{
cache.RouteMode = ModeQueue;
cache.StablePassCount = Math.Min(cache.StablePassCount, 0) - 1;
return Hold(
cache,
StrategyQueue,
Math.Max(1, _coordinatorSettings.HoldSecondsQueue),
waitNode,
$"occupy turn lost ({queuePos + 1}/{queueSize}), back to queue");
}
if (!string.Equals(waitNode, lastNode, StringComparison.OrdinalIgnoreCase) || driving)
{
return Hold(
cache,
StrategyQueue,
Math.Max(1, _coordinatorSettings.HoldSecondsQueue),
waitNode,
$"occupying junction and waiting robot settle (1/{queueSize})",
ModeOccupying);
}
var conflict = await ProbeConflictAsync(robotId, cache.MapCode, first);
if (conflict.HasConflict)
{
cache.StablePassCount = Math.Min(cache.StablePassCount, 0) - 1;
cache.ConsecutiveConflictFailCount = Math.Max(0, cache.ConsecutiveConflictFailCount) + 1;
if (cache.ConsecutiveConflictFailCount >= Math.Max(1, _coordinatorSettings.ConflictEscalateBlockedThreshold))
{
cache.RouteMode = ModeBlocked;
cache.BlockedReason = "occupying mode conflict escalated to blocked protection mode";
cache.LastDecisionCode = StrategyBlocked;
return Hold(
cache,
StrategyBlocked,
Math.Max(1, _coordinatorSettings.BlockedHoldSeconds),
waitNode,
$"blocked in occupying mode ({cache.ConsecutiveConflictFailCount})",
ModeBlocked);
}
return Hold(
cache,
StrategyQueue,
Math.Max(1, _coordinatorSettings.HoldSecondsQueue),
waitNode,
$"occupying and waiting junction release (1/{queueSize})",
ModeOccupying);
}
cache.StablePassCount = Math.Max(cache.StablePassCount, 0) + 1;
cache.ConsecutiveConflictFailCount = 0;
cache.BlockedReason = null;
if (cache.StablePassCount < Math.Max(1, _coordinatorSettings.ResumeStablePassThreshold))
{
return Hold(
cache,
StrategyQueue,
1,
waitNode,
$"occupying precheck pass not stable (1/{queueSize})",
ModeOccupying);
}
await ReleaseQueueTicketAsync(robotId, cache.MapCode, waitNode);
var trim = TryBuildTrimHeadPatch(cache, lastNode);
return trim != null ? Patch(trim, "occupying released trim") : Continue("occupying released");
}
/// <summary>
/// 处理阻塞保护态流程,通过受控等待与降频重试抑制冲突抖动扩散。
/// </summary>
private async Task<RouteAdjustmentDecision> HandleBlockedAsync(
Guid robotId,
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
string? lastNode,
bool driving,
CancellationToken ct)
{
var waitNode = cache.HoldNodeCode ?? first.FromNodeCode;
var atWaitNode = string.Equals(waitNode, lastNode, StringComparison.OrdinalIgnoreCase);
if (!atWaitNode || driving)
{
return Hold(
cache,
StrategyBlocked,
Math.Max(1, _coordinatorSettings.BlockedHoldSeconds),
waitNode,
"blocked mode waiting for robot stop",
ModeBlocked);
}
var conflict = await ProbeConflictAsync(robotId, cache.MapCode, first);
if (conflict.HasConflict)
{
cache.StablePassCount = Math.Min(cache.StablePassCount, 0) - 1;
cache.ConsecutiveConflictFailCount = Math.Max(0, cache.ConsecutiveConflictFailCount) + 1;
return Hold(
cache,
StrategyBlocked,
Math.Max(1, _coordinatorSettings.BlockedHoldSeconds),
waitNode,
"blocked mode conflict not cleared",
ModeBlocked);
}
cache.StablePassCount = Math.Max(cache.StablePassCount, 0) + 1;
if (cache.StablePassCount < Math.Max(1, _coordinatorSettings.ResumeStablePassThreshold))
{
return Hold(cache, StrategyBlocked, 1, waitNode, "blocked precheck pass not stable", ModeBlocked);
}
cache.RouteMode = ModeNormal;
cache.ConsecutiveConflictFailCount = 0;
cache.BlockedReason = null;
var trim = TryBuildTrimHeadPatch(cache, lastNode);
return trim != null ? Patch(trim, "blocked recovered and trim") : Continue("blocked recovered");
}
/// <summary>
/// 处理重规划待执行态,校验补丁可用性并在可发送与继续等待间切换。
/// </summary>
private async Task<RouteAdjustmentDecision> HandleReplanPendingAsync(
Guid robotId,
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
string? lastNode,
bool driving,
CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
var waitNode = cache.HoldNodeCode ?? first.FromNodeCode;
var atWaitNode = string.Equals(waitNode, lastNode, StringComparison.OrdinalIgnoreCase);
if (!atWaitNode || driving)
{
return Hold(
cache,
StrategyReplan,
Math.Max(1, _coordinatorSettings.HoldSecondsShort),
waitNode,
"replan pending mode waiting for robot stop",
ModeReplanPending);
}
if (cache.IsWaitingForNetAction)
{
return Hold(
cache,
StrategyReplan,
Math.Max(1, _coordinatorSettings.HoldSecondsShort),
waitNode,
"replan pending but net action in progress",
ModeReplanPending);
}
var conflict = await ProbeConflictAsync(robotId, cache.MapCode, first);
var patch = await TryBuildReplanTailPatchAsync(cache, first, conflict, lastNode);
if (patch != null)
{
cache.LastDecisionCode = StrategyReplan;
return Replan(patch, "replan pending patch");
}
cache.StablePassCount = Math.Min(cache.StablePassCount, 0) - 1;
cache.ConsecutiveConflictFailCount = Math.Max(0, cache.ConsecutiveConflictFailCount) + 1;
if (cache.ConsecutiveConflictFailCount >= Math.Max(1, _coordinatorSettings.ConflictEscalateBlockedThreshold))
{
cache.RouteMode = ModeBlocked;
cache.BlockedReason = "replan pending failed and escalated to blocked mode";
cache.LastDecisionCode = StrategyBlocked;
return Hold(
cache,
StrategyBlocked,
Math.Max(1, _coordinatorSettings.BlockedHoldSeconds),
waitNode,
"replan pending failed, blocked",
ModeBlocked);
}
return Hold(
cache,
StrategyReplan,
Math.Max(1, _coordinatorSettings.HoldSecondsShort),
waitNode,
"replan pending no feasible patch, keep waiting",
ModeReplanPending);
}
/// <summary>
/// 按候选策略顺序尝试构建升级决策,遵循由低成本到高成本的逐级退让原则。
/// </summary>
private async Task<RouteAdjustmentDecision?> TryBuildEscalationDecisionAsync(
Guid robotId,
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
ConflictProbe conflict,
string? lastNode,
string strategyCode)
{
switch (strategyCode)
{
case AvoidanceStrategyCodes.WaitNearest:
{
var patch = await TryBuildNearestWaitPatchAsync(robotId, cache, first, conflict);
if (patch == null) return null;
cache.RouteMode = ModeDetouring;
cache.LastDecisionCode = StrategyWait;
return Patch(patch, "nearest wait patch");
}
case AvoidanceStrategyCodes.LocalDetour:
{
var patch = await TryBuildLocalDetourPatchAsync(cache, first, conflict, lastNode);
if (patch == null) return null;
cache.RouteMode = ModeDetouring;
cache.LastDecisionCode = StrategyDetour;
return Patch(patch, "local detour patch");
}
case AvoidanceStrategyCodes.LateralYield:
{
var patch = await TryBuildLateralYieldPatchAsync(robotId, cache, first, conflict, lastNode);
if (patch == null) return null;
cache.RouteMode = ModeDetouring;
cache.LastDecisionCode = StrategyLateral;
return Patch(patch, "lateral yield patch");
}
case AvoidanceStrategyCodes.ParkingYield:
{
var patch = await TryBuildParkingYieldPatchAsync(robotId, cache, first, conflict, lastNode);
if (patch == null) return null;
cache.RouteMode = ModeDetouring;
cache.LastDecisionCode = StrategyParking;
return Patch(patch, "parking yield patch");
}
case AvoidanceStrategyCodes.Retreat:
{
var patch = await TryBuildRetreatPatchAsync(cache, first, conflict, lastNode);
if (patch == null) return null;
cache.RouteMode = ModeDetouring;
cache.LastDecisionCode = StrategyRetreat;
return Patch(patch, "retreat patch");
}
case AvoidanceStrategyCodes.ReplanTail:
{
var patch = await TryBuildReplanTailPatchAsync(cache, first, conflict, lastNode);
if (patch == null) return null;
cache.RouteMode = ModeReplanPending;
cache.HoldNodeCode ??= first.FromNodeCode;
cache.LastDecisionCode = StrategyReplan;
return Replan(patch, "full tail replan patch");
}
default:
return null;
}
}
/// <summary>
/// 探测首段节点/边占用与逆向冲突,形成后续决策所需的冲突画像。
/// </summary>
private async Task<ConflictProbe> ProbeConflictAsync(Guid robotId, string mapCode, PathSegmentWithCode first)
{
var nodeOccupied = !string.IsNullOrWhiteSpace(first.ToNodeCode) &&
await _trafficControl.IsNodeOccupiedByOtherAsync(mapCode, first.ToNodeCode, robotId);
var edgeOccupied = false;
var reverseConflict = false;
if (!string.IsNullOrWhiteSpace(first.EdgeCode))
{
var holder = await _trafficControl.GetEdgeLockHolderAsync(mapCode, first.EdgeCode);
edgeOccupied = holder.HasValue && holder.Value != robotId;
reverseConflict = await _trafficControl.HasReverseConflictAsync(
mapCode, first.EdgeCode, first.FromNodeCode, first.ToNodeCode, robotId);
}
return new ConflictProbe
{
HasConflict = nodeOccupied || edgeOccupied || reverseConflict,
HasReverseConflict = reverseConflict,
BlockingNodeCode = nodeOccupied ? first.ToNodeCode : null,
BlockingEdgeCode = edgeOccupied || reverseConflict ? first.EdgeCode : null
};
}
/// <summary>
/// 构建就近等待补丁,以最小改动原则优先保持原有主路径。
/// </summary>
private async Task<TailPatch?> TryBuildNearestWaitPatchAsync(
Guid robotId,
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
ConflictProbe conflict)
{
var graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId);
if (graph == null)
{
return null;
}
var startNodeCode = first.FromNodeCode;
var waitingNodes = graph.GetWaitingAreaNodes()
.Select(id => graph.Nodes.TryGetValue(id, out var node) ? node : null)
.Where(node => node != null)
.Select(node => node!)
.ToList();
if (waitingNodes.Count == 0)
{
return null;
}
var forbiddenNodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var forbiddenEdges = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(conflict.BlockingNodeCode)) forbiddenNodes.Add(conflict.BlockingNodeCode);
if (!string.IsNullOrWhiteSpace(conflict.BlockingEdgeCode)) forbiddenEdges.Add(conflict.BlockingEdgeCode);
var rejoinNodes = GetUnsentNodeCandidates(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex)
.Skip(1)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(8)
.ToList();
foreach (var waitNode in waitingNodes)
{
if (await _trafficControl.IsNodeOccupiedByOtherAsync(cache.MapCode, waitNode.NodeCode, robotId))
{
continue;
}
var p1 = FindNodeCodePath(graph, startNodeCode, waitNode.NodeCode, forbiddenNodes, forbiddenEdges, 24);
if (p1.Count == 0) continue;
foreach (var rejoin in rejoinNodes)
{
var p2 = FindNodeCodePath(graph, waitNode.NodeCode, rejoin, forbiddenNodes, forbiddenEdges, 28);
if (p2.Count == 0) continue;
if (!TryFindStartPosition(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex, rejoin, out var j, out var r, out var s))
{
continue;
}
var merged = p1.Select(CloneSegment).Concat(p2.Select(CloneSegment)).ToList();
RemoveDuplicateBoundary(merged);
if (merged.Count == 0) continue;
var suffix = BuildTailFromPosition(cache, j, r, s);
var newTail = BuildTailWithPrefix(merged, suffix);
if (newTail.Count == 0) continue;
return new TailPatch
{
ExpectedPlanVersion = cache.PlanVersion,
FromJunctionIndex = cache.CurrentJunctionIndex,
FromResourceIndex = cache.CurrentResourceIndex,
StrategyCode = StrategyWait,
Reason = $"nearest wait node {waitNode.NodeCode}",
WaitNodeCode = waitNode.NodeCode,
RejoinNodeCode = rejoin,
NewTail = newTail
};
}
}
return null;
}
/// <summary>
/// 构建侧向让行补丁,通过短距离偏移临时释放关键冲突点。
/// </summary>
private async Task<TailPatch?> TryBuildLateralYieldPatchAsync(
Guid robotId,
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
ConflictProbe conflict,
string? lastNode)
{
var graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId);
if (graph == null)
{
return null;
}
var startNodeCode = string.IsNullOrWhiteSpace(lastNode) ? first.FromNodeCode : lastNode;
var startNode = graph.Nodes.Values.FirstOrDefault(n =>
string.Equals(n.NodeCode, startNodeCode, StringComparison.OrdinalIgnoreCase));
if (startNode == null)
{
return null;
}
var forbiddenNodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var forbiddenEdges = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(conflict.BlockingNodeCode)) forbiddenNodes.Add(conflict.BlockingNodeCode);
if (!string.IsNullOrWhiteSpace(conflict.BlockingEdgeCode)) forbiddenEdges.Add(conflict.BlockingEdgeCode);
var lateralCandidates = graph.Nodes.Values
.Where(n => !string.Equals(n.NodeCode, startNodeCode, StringComparison.OrdinalIgnoreCase))
.Where(n =>
n.NodeCode.Contains("yield", StringComparison.OrdinalIgnoreCase) ||
n.NodeCode.Contains("side", StringComparison.OrdinalIgnoreCase) ||
n.NodeCode.Contains("lane", StringComparison.OrdinalIgnoreCase) ||
n.NodeCode.Contains("bay", StringComparison.OrdinalIgnoreCase))
.OrderBy(n => DistanceSquared(startNode, n))
.Take(12)
.ToList();
if (lateralCandidates.Count == 0)
{
return null;
}
var rejoinNodes = GetUnsentNodeCandidates(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex)
.Skip(2)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(8)
.ToList();
foreach (var lateralNode in lateralCandidates)
{
if (await _trafficControl.IsNodeOccupiedByOtherAsync(cache.MapCode, lateralNode.NodeCode, robotId))
{
continue;
}
var toLateral = FindNodeCodePath(graph, startNodeCode, lateralNode.NodeCode, forbiddenNodes, forbiddenEdges, 24);
if (toLateral.Count == 0)
{
continue;
}
foreach (var rejoin in rejoinNodes)
{
var toRejoin = FindNodeCodePath(graph, lateralNode.NodeCode, rejoin, forbiddenNodes, forbiddenEdges, 32);
if (toRejoin.Count == 0)
{
continue;
}
if (!TryFindStartPosition(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex, rejoin, out var j, out var r, out var s))
{
continue;
}
var merged = toLateral.Select(CloneSegment).Concat(toRejoin.Select(CloneSegment)).ToList();
RemoveDuplicateBoundary(merged);
if (merged.Count == 0)
{
continue;
}
var suffix = BuildTailFromPosition(cache, j, r, s);
var newTail = BuildTailWithPrefix(merged, suffix);
if (newTail.Count == 0)
{
continue;
}
return new TailPatch
{
ExpectedPlanVersion = cache.PlanVersion,
FromJunctionIndex = cache.CurrentJunctionIndex,
FromResourceIndex = cache.CurrentResourceIndex,
StrategyCode = StrategyLateral,
Reason = $"lateral yield via {lateralNode.NodeCode}",
WaitNodeCode = lateralNode.NodeCode,
RejoinNodeCode = rejoin,
NewTail = newTail
};
}
}
return null;
}
/// <summary>
/// 构建局部绕行补丁,在限定范围内绕过冲突区域并尽快回归主线。
/// </summary>
private async Task<TailPatch?> TryBuildLocalDetourPatchAsync(
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
ConflictProbe conflict,
string? lastNode)
{
var graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId);
if (graph == null)
{
return null;
}
var startNodeCode = string.IsNullOrWhiteSpace(lastNode) ? first.FromNodeCode : lastNode;
var forbiddenNodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var forbiddenEdges = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(conflict.BlockingNodeCode)) forbiddenNodes.Add(conflict.BlockingNodeCode);
if (!string.IsNullOrWhiteSpace(conflict.BlockingEdgeCode)) forbiddenEdges.Add(conflict.BlockingEdgeCode);
var rejoinNodes = GetUnsentNodeCandidates(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex)
.Skip(2)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(8)
.ToList();
foreach (var rejoin in rejoinNodes)
{
var detour = FindNodeCodePath(graph, startNodeCode, rejoin, forbiddenNodes, forbiddenEdges, 32);
if (detour.Count == 0) continue;
if (!TryFindStartPosition(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex, rejoin, out var j, out var r, out var s))
{
continue;
}
var suffix = BuildTailFromPosition(cache, j, r, s);
var newTail = BuildTailWithPrefix(detour, suffix);
if (newTail.Count == 0) continue;
return new TailPatch
{
ExpectedPlanVersion = cache.PlanVersion,
FromJunctionIndex = cache.CurrentJunctionIndex,
FromResourceIndex = cache.CurrentResourceIndex,
StrategyCode = StrategyDetour,
Reason = $"local detour to {rejoin}",
RejoinNodeCode = rejoin,
NewTail = newTail
};
}
return null;
}
/// <summary>
/// 构建泊车让行补丁,将机器人导入可停靠节点以降低主通道占用。
/// </summary>
private async Task<TailPatch?> TryBuildParkingYieldPatchAsync(
Guid robotId,
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
ConflictProbe conflict,
string? lastNode)
{
var graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId);
if (graph == null)
{
return null;
}
var startNodeCode = string.IsNullOrWhiteSpace(lastNode) ? first.FromNodeCode : lastNode;
var startNode = graph.Nodes.Values.FirstOrDefault(n =>
string.Equals(n.NodeCode, startNodeCode, StringComparison.OrdinalIgnoreCase));
if (startNode == null)
{
return null;
}
var forbiddenNodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var forbiddenEdges = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(conflict.BlockingNodeCode)) forbiddenNodes.Add(conflict.BlockingNodeCode);
if (!string.IsNullOrWhiteSpace(conflict.BlockingEdgeCode)) forbiddenEdges.Add(conflict.BlockingEdgeCode);
var parkingCandidates = graph.Nodes.Values
.Where(n => !string.Equals(n.NodeCode, startNodeCode, StringComparison.OrdinalIgnoreCase))
.Where(n =>
n.NodeCode.Contains("parking", StringComparison.OrdinalIgnoreCase) ||
n.NodeCode.Contains("wait", StringComparison.OrdinalIgnoreCase))
.OrderBy(n => DistanceSquared(startNode, n))
.Take(10)
.ToList();
if (parkingCandidates.Count == 0)
{
return null;
}
var rejoinNodes = GetUnsentNodeCandidates(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex)
.Skip(2)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(8)
.ToList();
foreach (var parkingNode in parkingCandidates)
{
if (await _trafficControl.IsNodeOccupiedByOtherAsync(cache.MapCode, parkingNode.NodeCode, robotId))
{
continue;
}
var toParking = FindNodeCodePath(graph, startNodeCode, parkingNode.NodeCode, forbiddenNodes, forbiddenEdges, 28);
if (toParking.Count == 0)
{
continue;
}
foreach (var rejoin in rejoinNodes)
{
var toRejoin = FindNodeCodePath(graph, parkingNode.NodeCode, rejoin, forbiddenNodes, forbiddenEdges, 36);
if (toRejoin.Count == 0)
{
continue;
}
if (!TryFindStartPosition(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex, rejoin, out var j, out var r, out var s))
{
continue;
}
var merged = toParking.Select(CloneSegment).Concat(toRejoin.Select(CloneSegment)).ToList();
RemoveDuplicateBoundary(merged);
if (merged.Count == 0)
{
continue;
}
var suffix = BuildTailFromPosition(cache, j, r, s);
var newTail = BuildTailWithPrefix(merged, suffix);
if (newTail.Count == 0)
{
continue;
}
return new TailPatch
{
ExpectedPlanVersion = cache.PlanVersion,
FromJunctionIndex = cache.CurrentJunctionIndex,
FromResourceIndex = cache.CurrentResourceIndex,
StrategyCode = StrategyParking,
Reason = $"parking yield via {parkingNode.NodeCode}",
WaitNodeCode = parkingNode.NodeCode,
RejoinNodeCode = rejoin,
NewTail = newTail
};
}
}
return null;
}
/// <summary>
/// 构建退让补丁,通过反向回撤扩展会车空间并降低对向死锁概率。
/// </summary>
private async Task<TailPatch?> TryBuildRetreatPatchAsync(
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
ConflictProbe conflict,
string? lastNode)
{
var graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId);
if (graph == null)
{
return null;
}
var startNodeCode = string.IsNullOrWhiteSpace(lastNode) ? first.FromNodeCode : lastNode;
var startNode = graph.Nodes.Values.FirstOrDefault(n =>
string.Equals(n.NodeCode, startNodeCode, StringComparison.OrdinalIgnoreCase));
if (startNode == null)
{
return null;
}
var forbiddenNodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var forbiddenEdges = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(conflict.BlockingNodeCode)) forbiddenNodes.Add(conflict.BlockingNodeCode);
if (!string.IsNullOrWhiteSpace(conflict.BlockingEdgeCode)) forbiddenEdges.Add(conflict.BlockingEdgeCode);
var retreatCandidates = startNode.InEdges
.Select(e => graph.Nodes.TryGetValue(e.FromNodeId, out var node) ? node : null)
.Where(node => node != null)
.Select(node => node!)
.OrderBy(n => n.OutEdges.Count >= 3 ? 1 : 0)
.ThenBy(n => DistanceSquared(startNode, n))
.Take(8)
.ToList();
if (retreatCandidates.Count == 0)
{
return null;
}
var rejoinNodes = GetUnsentNodeCandidates(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex)
.Skip(2)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(8)
.ToList();
foreach (var retreatNode in retreatCandidates)
{
var toRetreat = FindNodeCodePath(graph, startNodeCode, retreatNode.NodeCode, forbiddenNodes, forbiddenEdges, 20);
if (toRetreat.Count == 0)
{
continue;
}
foreach (var rejoin in rejoinNodes)
{
var toRejoin = FindNodeCodePath(graph, retreatNode.NodeCode, rejoin, forbiddenNodes, forbiddenEdges, 40);
if (toRejoin.Count == 0)
{
continue;
}
if (!TryFindStartPosition(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex, rejoin, out var j, out var r, out var s))
{
continue;
}
var merged = toRetreat.Select(CloneSegment).Concat(toRejoin.Select(CloneSegment)).ToList();
RemoveDuplicateBoundary(merged);
if (merged.Count == 0)
{
continue;
}
var suffix = BuildTailFromPosition(cache, j, r, s);
var newTail = BuildTailWithPrefix(merged, suffix);
if (newTail.Count == 0)
{
continue;
}
return new TailPatch
{
ExpectedPlanVersion = cache.PlanVersion,
FromJunctionIndex = cache.CurrentJunctionIndex,
FromResourceIndex = cache.CurrentResourceIndex,
StrategyCode = StrategyRetreat,
Reason = $"retreat via {retreatNode.NodeCode}",
WaitNodeCode = retreatNode.NodeCode,
RejoinNodeCode = rejoin,
NewTail = newTail
};
}
}
return null;
}
/// <summary>
/// 构建尾段重规划补丁,在局部策略无效时执行更全局的替代路径搜索。
/// </summary>
private async Task<TailPatch?> TryBuildReplanTailPatchAsync(
VdaSegmentedPathCache cache,
PathSegmentWithCode first,
ConflictProbe conflict,
string? lastNode)
{
var graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId);
if (graph == null || string.IsNullOrWhiteSpace(cache.OriginalGoalNodeCode))
{
return null;
}
var startNodeCode = string.IsNullOrWhiteSpace(lastNode) ? first.FromNodeCode : lastNode;
var goalNodeCode = cache.OriginalGoalNodeCode!;
var forbiddenNodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var forbiddenEdges = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(conflict.BlockingNodeCode)) forbiddenNodes.Add(conflict.BlockingNodeCode);
if (!string.IsNullOrWhiteSpace(conflict.BlockingEdgeCode)) forbiddenEdges.Add(conflict.BlockingEdgeCode);
var replanned = FindNodeCodePath(graph, startNodeCode, goalNodeCode, forbiddenNodes, forbiddenEdges, 120);
if (replanned.Count == 0)
{
// 如果严格禁用过滤后无可选路径,则尝试放宽条件进行全局重规划。
replanned = FindNodeCodePath(
graph,
startNodeCode,
goalNodeCode,
new HashSet<string>(StringComparer.OrdinalIgnoreCase),
new HashSet<string>(StringComparer.OrdinalIgnoreCase),
120);
}
if (replanned.Count == 0)
{
return null;
}
var newTail = BuildTailWithPrefix(replanned, new List<List<List<PathSegmentWithCode>>>());
if (newTail.Count == 0)
{
return null;
}
return new TailPatch
{
ExpectedPlanVersion = cache.PlanVersion,
FromJunctionIndex = cache.CurrentJunctionIndex,
FromResourceIndex = cache.CurrentResourceIndex,
StrategyCode = StrategyReplan,
Reason = $"full tail replan to goal {goalNodeCode}",
RejoinNodeCode = goalNodeCode,
NewTail = newTail
};
}
/// <summary>
/// 计算两个节点平面距离的平方值,用于候选点按近似距离排序。
/// </summary>
private static double DistanceSquared(PathNode from, PathNode to)
{
var dx = from.X - to.X;
var dy = from.Y - to.Y;
return dx * dx + dy * dy;
}
/// <summary>
/// 在禁用节点/边约束下执行图搜索,求解满足约束的节点编码路径。
/// </summary>
private static List<PathSegmentWithCode> FindNodeCodePath(
PathGraph graph,
string fromNodeCode,
string toNodeCode,
HashSet<string> forbiddenNodes,
HashSet<string> forbiddenEdges,
int maxHops)
{
if (string.Equals(fromNodeCode, toNodeCode, StringComparison.OrdinalIgnoreCase)) return new List<PathSegmentWithCode>();
var start = graph.Nodes.Values.FirstOrDefault(n => string.Equals(n.NodeCode, fromNodeCode, StringComparison.OrdinalIgnoreCase));
var target = graph.Nodes.Values.FirstOrDefault(n => string.Equals(n.NodeCode, toNodeCode, StringComparison.OrdinalIgnoreCase));
if (start == null || target == null) return new List<PathSegmentWithCode>();
var q = new Queue<Guid>();
var prev = new Dictionary<Guid, PathEdge>();
var depth = new Dictionary<Guid, int>();
var visited = new HashSet<Guid> { start.NodeId };
q.Enqueue(start.NodeId);
depth[start.NodeId] = 0;
while (q.Count > 0)
{
var currentId = q.Dequeue();
if (!graph.Nodes.TryGetValue(currentId, out var current)) continue;
if (depth[currentId] >= maxHops) continue;
foreach (var edge in current.OutEdges)
{
if (forbiddenEdges.Contains(edge.EdgeCode)) continue;
if (!graph.Nodes.TryGetValue(edge.ToNodeId, out var next)) continue;
if (!string.Equals(next.NodeCode, toNodeCode, StringComparison.OrdinalIgnoreCase) && forbiddenNodes.Contains(next.NodeCode)) continue;
if (!visited.Add(next.NodeId)) continue;
prev[next.NodeId] = edge;
depth[next.NodeId] = depth[currentId] + 1;
if (next.NodeId == target.NodeId)
{
return RebuildPath(prev, start.NodeId, target.NodeId);
}
q.Enqueue(next.NodeId);
}
}
return new List<PathSegmentWithCode>();
}
/// <summary>
/// 根据前驱关系逆向回溯并重建连续路径段,确保结果可用于补丁下发。
/// </summary>
private static List<PathSegmentWithCode> RebuildPath(Dictionary<Guid, PathEdge> prev, Guid startId, Guid endId)
{
var edges = new List<PathEdge>();
var cursor = endId;
while (cursor != startId)
{
if (!prev.TryGetValue(cursor, out var edge))
{
return new List<PathSegmentWithCode>();
}
edges.Add(edge);
cursor = edge.FromNodeId;
}
edges.Reverse();
return edges.Select(edge => new PathSegmentWithCode
{
EdgeId = edge.EdgeId,
FromNodeId = edge.FromNodeId,
ToNodeId = edge.ToNodeId,
Length = edge.Length,
MaxSpeed = edge.MaxSpeed,
RequiredAngle = 0,
Angle = 0,
StartTheta = 0,
EndTheta = edge.DirectionRad,
EdgeCode = edge.EdgeCode,
FromNodeCode = edge.FromNodeCode,
ToNodeCode = edge.ToNodeCode,
StartNodeActions = new List<StepAction>(),
EndNodeActions = new List<StepAction>(),
StartNodeNetActionTypes = new Dictionary<Guid, ActionType>(),
EndNodeNetActionTypes = new Dictionary<Guid, ActionType>()
}).ToList();
}
/// <summary>
/// 移除拼接边界重复段,保证补丁路径拓扑连续且无冗余跳变。
/// </summary>
private static void RemoveDuplicateBoundary(List<PathSegmentWithCode> segments)
{
for (var i = segments.Count - 1; i > 0; i--)
{
var a = segments[i - 1];
var b = segments[i];
if (string.Equals(a.EdgeCode, b.EdgeCode, StringComparison.OrdinalIgnoreCase) &&
string.Equals(a.FromNodeCode, b.FromNodeCode, StringComparison.OrdinalIgnoreCase) &&
string.Equals(a.ToNodeCode, b.ToNodeCode, StringComparison.OrdinalIgnoreCase))
{
segments.RemoveAt(i);
}
}
}
/// <summary>
/// 合并保留前缀与新尾段,确保已发送区域不被覆盖且未发送区域可替换。
/// </summary>
private static List<List<List<PathSegmentWithCode>>> BuildTailWithPrefix(
List<PathSegmentWithCode> prefix,
List<List<List<PathSegmentWithCode>>> suffix)
{
var tail = new List<List<List<PathSegmentWithCode>>>();
if (prefix.Count > 0)
{
tail.Add(new List<List<PathSegmentWithCode>> { prefix.Select(CloneSegment).ToList() });
}
tail.AddRange(suffix.Select(j => j.Select(r => r.Select(CloneSegment).ToList()).ToList()));
return tail;
}
/// <summary>
/// 提取未发送区域节点候选集,为等待点与让行点筛选提供输入。
/// </summary>
private static List<string> GetUnsentNodeCandidates(VdaSegmentedPathCache cache, int fromJunction, int fromResource)
{
var nodes = new List<string>();
var firstAdded = false;
for (var j = fromJunction; j < cache.JunctionSegments.Count; j++)
{
var resources = cache.JunctionSegments[j].ResourceSegments;
var rStart = j == fromJunction ? fromResource : 0;
for (var r = rStart; r < resources.Count; r++)
{
var segs = resources[r].Segments;
if (segs.Count == 0) continue;
if (!firstAdded)
{
nodes.Add(segs[0].FromNodeCode);
firstAdded = true;
}
nodes.AddRange(segs.Select(s => s.ToNodeCode));
}
}
return nodes.Where(code => !string.IsNullOrWhiteSpace(code)).ToList()!;
}
/// <summary>
/// 基于 Redis 有序集合确保队列票据原子存在并返回序位,支撑公平排队。
/// </summary>
private async Task<(int Position, int Size)> EnsureQueueTicketAsync(
Guid robotId,
string mapCode,
string queueNodeCode,
CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(mapCode) || string.IsNullOrWhiteSpace(queueNodeCode))
{
return (0, 1);
}
ct.ThrowIfCancellationRequested();
var db = _redis.GetDatabase();
var orderKey = BuildQueueOrderKey(mapCode, queueNodeCode);
var aliveKey = BuildQueueAliveKey(mapCode, queueNodeCode);
var member = BuildQueueMember(robotId);
var nowMs = DateTimeOffset.Now.ToUnixTimeMilliseconds();
var staleSeconds = Math.Max(10, _coordinatorSettings.QueueStaleSeconds);
var staleBeforeMs = nowMs - staleSeconds * 1000L;
var staleMembers = await db.SortedSetRangeByScoreAsync(aliveKey, double.NegativeInfinity, staleBeforeMs);
if (staleMembers.Length > 0)
{
await db.SortedSetRemoveAsync(aliveKey, staleMembers);
await db.SortedSetRemoveAsync(orderKey, staleMembers);
}
await db.SortedSetAddAsync(orderKey, member, nowMs, when: When.NotExists);
await db.SortedSetAddAsync(aliveKey, member, nowMs, when: When.Always);
var ttl = TimeSpan.FromSeconds(staleSeconds * 2);
await db.KeyExpireAsync(orderKey, ttl);
await db.KeyExpireAsync(aliveKey, ttl);
var rank = await db.SortedSetRankAsync(orderKey, member, Order.Ascending);
var count = await db.SortedSetLengthAsync(orderKey);
return ((int)(rank ?? 0), (int)Math.Max(1, count));
}
/// <summary>
/// 释放完成或失效的队列票据,避免僵尸成员影响后续排队公平性。
/// </summary>
private async Task ReleaseQueueTicketAsync(Guid robotId, string mapCode, string? queueNodeCode)
{
if (string.IsNullOrWhiteSpace(mapCode) || string.IsNullOrWhiteSpace(queueNodeCode))
{
return;
}
var db = _redis.GetDatabase();
var member = BuildQueueMember(robotId);
await db.SortedSetRemoveAsync(BuildQueueOrderKey(mapCode, queueNodeCode), member);
await db.SortedSetRemoveAsync(BuildQueueAliveKey(mapCode, queueNodeCode), member);
}
/// <summary>
/// 构建队列顺序 Key,按地图与节点维度进行隔离。
/// </summary>
private static string BuildQueueOrderKey(string mapCode, string queueNodeCode)
=> $"{QueueKeyPrefix}:{mapCode}:{queueNodeCode}:order";
/// <summary>
/// 构建队列存活 Key,用于成员活性续期与过期清理。
/// </summary>
private static string BuildQueueAliveKey(string mapCode, string queueNodeCode)
=> $"{QueueKeyPrefix}:{mapCode}:{queueNodeCode}:alive";
/// <summary>
/// 将机器人标识规范化为队列成员字符串,保证跨进程一致识别。
/// </summary>
private static string BuildQueueMember(Guid robotId) => robotId.ToString("N");
/// <summary>
/// 融合快照状态与调用参数,优先采用更新鲜数据以降低决策误判。
/// </summary>
private (string? LastNodeCode, bool IsDriving) ResolveRuntime(Guid robotId, string? lastNodeCode, bool isDriving)
{
var effectiveLastNode = lastNodeCode;
var effectiveDriving = isDriving;
if ((string.IsNullOrWhiteSpace(effectiveLastNode) || !isDriving) &&
_robotSnapshots.TryGetValue(robotId, out var snapshot))
{
if (string.IsNullOrWhiteSpace(effectiveLastNode)) effectiveLastNode = snapshot.LastNodeCode;
if (!isDriving) effectiveDriving = snapshot.IsDriving;
}
return (effectiveLastNode, effectiveDriving);
}
/// <summary>
/// 判断近期逆向冲突是否成立,用于触发更保守的升级策略。
/// </summary>
private bool HasRecentReverseConflictSignal(Guid robotId, string mapCode)
{
if (!_lockConflictSnapshots.TryGetValue(robotId, out var snapshot))
{
return false;
}
if (!string.IsNullOrWhiteSpace(snapshot.MapCode) &&
!string.IsNullOrWhiteSpace(mapCode) &&
!string.Equals(snapshot.MapCode, mapCode, StringComparison.OrdinalIgnoreCase))
{
return false;
}
var age = DateTime.Now - snapshot.LastOccurredAtUtc;
if (age > TimeSpan.FromSeconds(20))
{
_lockConflictSnapshots.TryRemove(robotId, out _);
return false;
}
return snapshot.ReverseConflictStreak > 0;
}
/// <summary>
/// 构造继续发送决策,表示当前无需路径调整。
/// </summary>
private RouteAdjustmentDecision Continue(string message) =>
TrackDecision(new RouteAdjustmentDecision
{
Action = RouteAdjustmentAction.Continue,
StrategyCode = StrategyContinue,
Message = message
});
/// <summary>
/// 构造补丁决策,在不重发已发送段前提下替换未发送尾段。
/// </summary>
private RouteAdjustmentDecision Patch(TailPatch patch, string message) =>
TrackDecision(new RouteAdjustmentDecision
{
Action = RouteAdjustmentAction.PatchTail,
StrategyCode = patch.StrategyCode,
Patch = patch,
Message = message
});
/// <summary>
/// 构造重规划决策,适用于局部避让无法消解冲突的场景。
/// </summary>
private RouteAdjustmentDecision Replan(TailPatch patch, string message) =>
TrackDecision(new RouteAdjustmentDecision
{
Action = RouteAdjustmentAction.ReplanTail,
StrategyCode = patch.StrategyCode,
Patch = patch,
Message = message
});
/// <summary>
/// 构造等待决策并写入等待窗口,利用时间缓冲抑制高频冲突重试。
/// </summary>
private RouteAdjustmentDecision Hold(
VdaSegmentedPathCache cache,
string strategyCode,
int holdSeconds,
string holdNodeCode,
string message,
string? routeModeOverride = null)
{
var holdUntil = DateTime.Now.AddSeconds(Math.Max(1, holdSeconds));
cache.RouteMode = routeModeOverride ??
(string.Equals(strategyCode, StrategyQueue, StringComparison.Ordinal) ? ModeQueue : ModeHold);
cache.HoldNodeCode = holdNodeCode;
cache.HoldUntilUtc = holdUntil;
cache.LastDecisionCode = strategyCode;
return TrackDecision(new RouteAdjustmentDecision
{
Action = RouteAdjustmentAction.Hold,
StrategyCode = strategyCode,
SuggestedHoldUntilUtc = holdUntil,
Message = message
});
}
/// <summary>
/// 记录决策计数与策略命中分布,为运行观测和参数优化提供指标。
/// </summary>
private RouteAdjustmentDecision TrackDecision(RouteAdjustmentDecision decision)
{
switch (decision.Action)
{
case RouteAdjustmentAction.Hold:
System.Threading.Interlocked.Increment(ref _decisionHoldCount);
break;
case RouteAdjustmentAction.PatchTail:
case RouteAdjustmentAction.ReplanTail:
System.Threading.Interlocked.Increment(ref _decisionPatchCount);
break;
default:
System.Threading.Interlocked.Increment(ref _decisionContinueCount);
break;
}
var strategy = string.IsNullOrWhiteSpace(decision.StrategyCode) ? "Unknown" : decision.StrategyCode;
_decisionStrategyCounts.AddOrUpdate(strategy, 1, (_, oldValue) => oldValue + 1);
MaybeLogDecisionMetrics();
return decision;
}
/// <summary>
/// 按时间窗口输出决策统计,便于发现策略偏斜与异常波动。
/// </summary>
private void MaybeLogDecisionMetrics()
{
var now = DateTime.Now;
if (now - _lastDecisionMetricsLogUtc < _decisionMetricsLogInterval)
{
return;
}
_lastDecisionMetricsLogUtc = now;
var topStrategies = string.Join(",",
_decisionStrategyCounts
.OrderByDescending(item => item.Value)
.Take(5)
.Select(item => $"{item.Key}:{item.Value}"));
_logger.LogInformation(
"[全局导航] 决策指标: Continue={Continue}, Hold={Hold}, Patch={Patch}, TopStrategies={TopStrategies}",
System.Threading.Interlocked.Read(ref _decisionContinueCount),
System.Threading.Interlocked.Read(ref _decisionHoldCount),
System.Threading.Interlocked.Read(ref _decisionPatchCount),
string.IsNullOrWhiteSpace(topStrategies) ? "-" : topStrategies);
}
/// <summary>
/// 按机器人实际进度裁剪过时头段,避免重复下发历史路径。
/// </summary>
private static TailPatch? TryBuildTrimHeadPatch(VdaSegmentedPathCache cache, string? lastNodeCode)
{
if (string.IsNullOrWhiteSpace(lastNodeCode)) return null;
if (cache.CurrentJunctionIndex >= cache.JunctionSegments.Count) return null;
var first = GetFirstUnsentSegment(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex);
if (first == null || string.Equals(first.FromNodeCode, lastNodeCode, StringComparison.OrdinalIgnoreCase)) return null;
if (!TryFindStartPosition(cache, cache.CurrentJunctionIndex, cache.CurrentResourceIndex, lastNodeCode, out var j, out var r, out var s))
{
return null;
}
if (j == cache.CurrentJunctionIndex && r == cache.CurrentResourceIndex && s == 0) return null;
var tail = BuildTailFromPosition(cache, j, r, s);
if (tail.Count == 0) return null;
return new TailPatch
{
ExpectedPlanVersion = cache.PlanVersion,
FromJunctionIndex = cache.CurrentJunctionIndex,
FromResourceIndex = cache.CurrentResourceIndex,
StrategyCode = StrategyTrim,
Reason = $"align unsent tail from {lastNodeCode}",
RejoinNodeCode = lastNodeCode,
NewTail = tail
};
}
/// <summary>
/// 定位未发送区域首段,作为冲突探测与策略计算的基准输入。
/// </summary>
private static PathSegmentWithCode? GetFirstUnsentSegment(VdaSegmentedPathCache cache, int fromJunction, int fromResource)
{
for (var j = fromJunction; j < cache.JunctionSegments.Count; j++)
{
var resources = cache.JunctionSegments[j].ResourceSegments;
var rStart = j == fromJunction ? fromResource : 0;
for (var r = rStart; r < resources.Count; r++)
{
var seg = resources[r].Segments.FirstOrDefault();
if (seg != null) return seg;
}
}
return null;
}
/// <summary>
/// 在缓存路径中定位节点对应发送起点,为裁剪与回归计算提供锚点。
/// </summary>
private static bool TryFindStartPosition(
VdaSegmentedPathCache cache,
int fromJunction,
int fromResource,
string nodeCode,
out int startJunction,
out int startResource,
out int startSegment)
{
startJunction = -1;
startResource = -1;
startSegment = -1;
for (var j = fromJunction; j < cache.JunctionSegments.Count; j++)
{
var resources = cache.JunctionSegments[j].ResourceSegments;
var rStart = j == fromJunction ? fromResource : 0;
for (var r = rStart; r < resources.Count; r++)
{
var segs = resources[r].Segments;
for (var s = 0; s < segs.Count; s++)
{
if (string.Equals(segs[s].FromNodeCode, nodeCode, StringComparison.OrdinalIgnoreCase))
{
startJunction = j;
startResource = r;
startSegment = s;
return true;
}
if (!string.Equals(segs[s].ToNodeCode, nodeCode, StringComparison.OrdinalIgnoreCase)) continue;
if (s + 1 < segs.Count)
{
startJunction = j;
startResource = r;
startSegment = s + 1;
return true;
}
if (TryFindNextNonEmptyResource(cache, j, r + 1, out startJunction, out startResource))
{
startSegment = 0;
return true;
}
}
}
}
return false;
}
/// <summary>
/// 从指定位置向后查找首个非空资源段,保证补丁起点有效。
/// </summary>
private static bool TryFindNextNonEmptyResource(VdaSegmentedPathCache cache, int junctionIndex, int fromResource, out int nextJunction, out int nextResource)
{
nextJunction = -1;
nextResource = -1;
for (var j = junctionIndex; j < cache.JunctionSegments.Count; j++)
{
var resources = cache.JunctionSegments[j].ResourceSegments;
var rStart = j == junctionIndex ? fromResource : 0;
for (var r = rStart; r < resources.Count; r++)
{
if (resources[r].Segments.Count == 0) continue;
nextJunction = j;
nextResource = r;
return true;
}
}
return false;
}
/// <summary>
/// 从指定坐标重建尾段三层结构,保持与缓存组织形式一致。
/// </summary>
private static List<List<List<PathSegmentWithCode>>> BuildTailFromPosition(VdaSegmentedPathCache cache, int startJunction, int startResource, int startSegment)
{
var newTail = new List<List<List<PathSegmentWithCode>>>();
for (var j = startJunction; j < cache.JunctionSegments.Count; j++)
{
var patchJ = new List<List<PathSegmentWithCode>>();
var rStart = j == startJunction ? startResource : 0;
for (var r = rStart; r < cache.JunctionSegments[j].ResourceSegments.Count; r++)
{
var src = cache.JunctionSegments[j].ResourceSegments[r].Segments;
if (src.Count == 0) continue;
var sStart = j == startJunction && r == startResource ? startSegment : 0;
if (sStart >= src.Count) continue;
patchJ.Add(src.Skip(sStart).Select(CloneSegment).ToList());
}
if (patchJ.Count > 0) newTail.Add(patchJ);
}
return newTail;
}
/// <summary>
/// 深拷贝原子路径段及动作集合,避免引用共享导致状态污染。
/// </summary>
private static PathSegmentWithCode CloneSegment(PathSegmentWithCode segment) =>
new()
{
EdgeId = segment.EdgeId,
FromNodeId = segment.FromNodeId,
ToNodeId = segment.ToNodeId,
Angle = segment.Angle,
Length = segment.Length,
MaxSpeed = segment.MaxSpeed,
RequiredAngle = segment.RequiredAngle,
StartTheta = segment.StartTheta,
EndTheta = segment.EndTheta,
EdgeCode = segment.EdgeCode,
FromNodeCode = segment.FromNodeCode,
ToNodeCode = segment.ToNodeCode,
ForkAngleOffset = segment.ForkAngleOffset,
StartNodeActions = new List<StepAction>(segment.StartNodeActions),
StartNodeNetActionTypes = new Dictionary<Guid, ActionType>(segment.StartNodeNetActionTypes),
EndNodeActions = new List<StepAction>(segment.EndNodeActions),
EndNodeNetActionTypes = new Dictionary<Guid, ActionType>(segment.EndNodeNetActionTypes)
};
/// <summary>
/// 后台消费状态事件并更新运行快照,利用单读通道保证处理时序一致。
/// </summary>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var evt in _stateEvents.Reader.ReadAllAsync(stoppingToken))
{
_robotSnapshots[evt.RobotId] = new RobotNavSnapshot
{
LastNodeCode = evt.LastNodeCode,
IsDriving = evt.IsDriving,
UpdatedAtUtc = evt.OccurredAtUtc
};
}
}
/// <summary>
/// 释放订阅等资源,避免热更新后重复回调与资源泄漏。
/// </summary>
public override void Dispose()
{
_settingsChangeSubscription?.Dispose();
base.Dispose();
}
private sealed class ConflictProbe
{
/// <summary>
/// 是否存在冲突。
/// </summary>
public bool HasConflict { get; set; }
/// <summary>
/// 是否存在逆向冲突。
/// </summary>
public bool HasReverseConflict { get; set; }
/// <summary>
/// 阻塞节点编码。
/// </summary>
public string? BlockingNodeCode { get; set; }
/// <summary>
/// 阻塞边编码。
/// </summary>
public string? BlockingEdgeCode { get; set; }
}
private sealed class RobotNavSnapshot
{
/// <summary>
/// 最后节点编码。
/// </summary>
public string? LastNodeCode { get; set; }
/// <summary>
/// 是否行驶中。
/// </summary>
public bool IsDriving { get; set; }
/// <summary>
/// 快照更新时间(UTC)。
/// </summary>
public DateTime UpdatedAtUtc { get; set; }
}
private sealed class LockConflictSnapshot
{
/// <summary>
/// 地图编码。
/// </summary>
public string? MapCode { get; set; }
/// <summary>
/// 最近冲突节点编码。
/// </summary>
public string? LastNodeCode { get; set; }
/// <summary>
/// 最近冲突边编码。
/// </summary>
public string? LastEdgeCode { get; set; }
/// <summary>
/// 最近失败原因。
/// </summary>
public string? LastFailureReason { get; set; }
/// <summary>
/// 最近冲突发生时间(UTC)。
/// </summary>
public DateTime LastOccurredAtUtc { get; set; }
/// <summary>
/// 连续逆向冲突次数。
/// </summary>
public int ReverseConflictStreak { get; set; }
/// <summary>
/// 连续总冲突次数。
/// </summary>
public int TotalConflictStreak { get; set; }
}
}