#
Administrator
9 天以前 dd891ef35f89458f0579fcebffb2c68e1a0772d3
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
package com.zy.common.utils;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
 
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zy.asrs.entity.BasDevp;
import com.zy.asrs.entity.BasStation;
import com.zy.asrs.service.BasDevpService;
import com.zy.asrs.service.BasStationService;
import com.zy.core.News;
import com.zy.core.model.StationObjModel;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.core.common.SpringUtils;
import com.core.exception.CoolException;
import com.zy.common.model.NavigateNode;
import com.zy.asrs.entity.DeviceConfig;
import com.zy.asrs.service.DeviceConfigService;
import com.zy.core.cache.SlaveConnection;
import com.zy.core.enums.SlaveType;
import com.zy.core.model.protocol.StationProtocol;
import com.zy.core.thread.StationThread;
import com.zy.system.entity.Config;
import com.zy.system.service.ConfigService;
 
@Component
public class NavigateUtils {
    private static final long STATION_PATH_RUNTIME_SNAPSHOT_TTL_MS = 2000L;
 
    private static final String CFG_STATION_PATH_LEN_WEIGHT_PERCENT = "stationPathLenWeightPercent";
    private static final String CFG_STATION_PATH_CONG_WEIGHT_PERCENT = "stationPathCongWeightPercent";
    private static final String CFG_STATION_PATH_PASS_OTHER_OUT_STATION_WEIGHT_PERCENT = "stationPathPassOtherOutStationWeightPercent";
    private static final String CFG_STATION_PATH_PASS_OTHER_OUT_STATION_FORCE_SKIP = "stationPathPassOtherOutStationForceSkip";
 
    @Autowired
    private BasStationService basStationService;
 
    private final AtomicReference<CachedStationPathRuntimeSnapshot> runtimeSnapshotRef = new AtomicReference<>();
 
    @Scheduled(fixedDelay = 1500, initialDelay = 3000)
    public void refreshStationPathCaches() {
        try {
            runtimeSnapshotRef.set(new CachedStationPathRuntimeSnapshot(System.currentTimeMillis(), buildStationPathRuntimeSnapshot()));
        } catch (Exception ignore) {
        }
    }
 
    public List<NavigateNode> calcByStationId(Integer startStationId, Integer endStationId) {
        BasStation startStation = basStationService.selectById(startStationId);
        if (startStation == null) {
            throw new CoolException("未找到该 起点 对应的站点数据");
        }
        Integer lev = startStation.getStationLev();
 
        NavigateSolution navigateSolution = new NavigateSolution();
        List<List<NavigateNode>> stationMap = navigateSolution.getStationMap(lev);
 
        NavigateNode startNode = navigateSolution.findStationNavigateNode(stationMap, startStationId);
        if (startNode == null) {
            throw new CoolException("未找到该 起点 对应的节点");
        }
 
        NavigateNode endNode = navigateSolution.findStationNavigateNode(stationMap, endStationId);
        if (endNode == null) {
            throw new CoolException("未找到该 终点 对应的节点");
        }
 
        long startTime = System.currentTimeMillis();
        News.info("[WCS Debug] 站点路径开始计算,startStationId={},endStationId={}", startStationId, endStationId);
        List<List<NavigateNode>> allList = navigateSolution.allSimplePaths(stationMap, startNode, endNode, 120, 500, 300);
        if (allList.isEmpty()) {
//            throw new CoolException("未找到该路径");
            return new ArrayList<>();
        }
        News.info("[WCS Debug] 站点路径计算完成,耗时:{}ms", System.currentTimeMillis() - startTime);
 
        startTime = System.currentTimeMillis();
        News.info("[WCS Debug] 站点路径权重开始分析,startStationId={},endStationId={}", startStationId, endStationId);
        List<NavigateNode> list = findStationBestPath(allList);
        News.info("[WCS Debug] 站点路径权重分析完成,耗时:{}ms", System.currentTimeMillis() - startTime);
 
        //去重
        HashSet<Integer> set = new HashSet<>();
        List<NavigateNode> fitlerList = new ArrayList<>();
        for (NavigateNode navigateNode : list) {
            JSONObject valuObject = JSON.parseObject(navigateNode.getNodeValue());
            if (valuObject.containsKey("rgvCalcFlag")) {
                continue;
            }
            if (set.add(valuObject.getInteger("stationId"))) {
                fitlerList.add(navigateNode);
            }
        }
 
        for (int i = 0; i < fitlerList.size(); i++) {
            NavigateNode currentNode = fitlerList.get(i);
            currentNode.setIsInflectionPoint(false);
            currentNode.setIsLiftTransferPoint(false);
 
            try {
                JSONObject valueObject = JSON.parseObject(currentNode.getNodeValue());
                if (valueObject != null) {
                    Object isLiftTransfer = valueObject.get("isLiftTransfer");
                    if (isLiftTransfer != null) {
                        String isLiftTransferStr = isLiftTransfer.toString();
                        if ("1".equals(isLiftTransferStr) || "true".equalsIgnoreCase(isLiftTransferStr)) {
                            currentNode.setIsLiftTransferPoint(true);
                        }
                    }
                }
            } catch (Exception ignore) {}
 
            NavigateNode nextNode = (i + 1 < fitlerList.size()) ? fitlerList.get(i + 1) : null;
            NavigateNode prevNode = (i - 1 >= 0) ? fitlerList.get(i - 1) : null;
 
            HashMap<String, Object> result = searchInflectionPoint(currentNode, nextNode, prevNode);
            if (Boolean.parseBoolean(result.get("result").toString())) {
                currentNode.setIsInflectionPoint(true);
                currentNode.setDirection(result.get("direction").toString());
            }
        }
 
        return fitlerList;
    }
 
    public List<NavigateNode> calcReachablePathByStationId(Integer startStationId, Integer endStationId) {
        BasStation startStation = basStationService.selectById(startStationId);
        if (startStation == null) {
            throw new CoolException("未找到该 起点 对应的站点数据");
        }
        Integer lev = startStation.getStationLev();
 
        NavigateSolution navigateSolution = new NavigateSolution();
        List<List<NavigateNode>> stationMap = navigateSolution.getStationMap(lev);
 
        NavigateNode startNode = navigateSolution.findStationNavigateNode(stationMap, startStationId);
        if (startNode == null) {
            throw new CoolException("未找到该 起点 对应的节点");
        }
 
        NavigateNode endNode = navigateSolution.findStationNavigateNode(stationMap, endStationId);
        if (endNode == null) {
            throw new CoolException("未找到该 终点 对应的节点");
        }
 
        long startTime = System.currentTimeMillis();
        News.info("[WCS Debug] 站点快速可达路径开始计算,startStationId={},endStationId={}", startStationId, endStationId);
        NavigateNode resNode = navigateSolution.astarSearchJava(stationMap, startNode, endNode);
        if (resNode == null) {
            return new ArrayList<>();
        }
        News.info("[WCS Debug] 站点快速可达路径计算完成,耗时:{}ms", System.currentTimeMillis() - startTime);
 
        return buildStationPathFromFatherChain(resNode, stationMap);
    }
 
    public List<NavigateNode> calcByTrackSiteNo(int lev, Integer startTrackSiteNo, Integer endTrackSiteNo) {
        NavigateSolution navigateSolution = new NavigateSolution();
        List<List<NavigateNode>> rgvTrackMap = navigateSolution.getRgvTrackMap(lev);
 
        NavigateNode startNode = navigateSolution.findTrackSiteNoNavigateNode(rgvTrackMap, startTrackSiteNo);
        if (startNode == null){
            throw new CoolException("未找到该 起点 对应的节点");
        }
 
        NavigateNode endNode = navigateSolution.findTrackSiteNoNavigateNode(rgvTrackMap, endTrackSiteNo);
        if (endNode == null){
            throw new CoolException("未找到该 终点 对应的节点");
        }
 
        long startTime = System.currentTimeMillis();
        News.info("[WCS Debug] RGV路径开始计算,startTrackSiteNo:{},endTrackSiteNo={}", startTrackSiteNo, endTrackSiteNo);
        NavigateNode res_node = navigateSolution.astarSearchJava(rgvTrackMap, startNode, endNode);
        if (res_node == null) {
//            throw new CoolException("未找到该路径");
            return new ArrayList<>();
        }
        News.info("[WCS Debug] RGV路径计算完成,耗时:{}ms", System.currentTimeMillis() - startTime);
 
        ArrayList<NavigateNode> list = new ArrayList<>();
        // 使用 visited 集合防止父链出现环导致死循环,同时设置安全步数上限
        HashSet<NavigateNode> visited = new HashSet<>();
        int maxSteps = rgvTrackMap.size() * rgvTrackMap.get(0).size() + 5; // 安全上限
        int steps = 0;
        NavigateNode fatherNode = null;//当前循环上一节点,用于拐点计算
        while (res_node != null && visited.add(res_node) && steps++ < maxSteps) {
            res_node.setIsInflectionPoint(false);
 
            //寻找拐点
            HashMap<String, Object> result = searchInflectionPoint(res_node, fatherNode, res_node.getFather());//分别传入当前节点、父节点、下一节点
            //判断当前节点是否为拐点
            if (Boolean.parseBoolean(result.get("result").toString())) {
                //当前为拐点
                res_node.setIsInflectionPoint(true);
                //拐点方向
                res_node.setDirection(result.get("direction").toString());
            }
 
            list.add(res_node);
            fatherNode = res_node;//把当前节点保存成一个父节点
            res_node = res_node.getFather();//迭代操作
        }
        if (steps >= maxSteps) {
            throw new CoolException("路径回溯超出安全上限,疑似存在父链循环");
        }
        Collections.reverse(list);
        //将每个节点里面的fatherNode至为null(方便后续计算时父节点过多导致显示的节点太多)
        for (NavigateNode navigateNode : list) {
            //父节点设置为null,不影响计算结果,不影响后续操作。
            //此操作仅为后续排查处理提供视觉方便。
            navigateNode.setFather(null);
        }
 
        //去重
        HashSet<Integer> set = new HashSet<>();
        List<NavigateNode> fitlerList = new ArrayList<>();
        for(NavigateNode navigateNode : list){
            JSONObject valuObject = JSON.parseObject(navigateNode.getNodeValue());
            if(set.add(valuObject.getInteger("trackSiteNo"))){
                fitlerList.add(navigateNode);
            }
        }
 
        return fitlerList;
    }
 
    public List<NavigateNode> findLiftStationList(int lev) {
        NavigateSolution navigateSolution = new NavigateSolution();
        List<List<NavigateNode>> stationMap = navigateSolution.getStationMap(lev);
 
        List<NavigateNode> liftStationList = new ArrayList<>();
        for (List<NavigateNode> navigateNodes : stationMap) {
            for (NavigateNode navigateNode : navigateNodes) {
                String nodeType = navigateNode.getNodeType();
                if(nodeType == null){
                    continue;
                }
                if(!nodeType.equals("devp")){
                    continue;
                }
                JSONObject valuObject = JSON.parseObject(navigateNode.getNodeValue());
                if(valuObject == null){
                    continue;
                }
                if (valuObject.containsKey("liftNo")) {
                    liftStationList.add(navigateNode);
                }
            }
        }
 
        return liftStationList;
    }
 
    private List<NavigateNode> buildStationPathFromFatherChain(NavigateNode endNode, List<List<NavigateNode>> stationMap) {
        ArrayList<NavigateNode> list = new ArrayList<>();
        HashSet<NavigateNode> visited = new HashSet<>();
        int maxSteps = stationMap.size() * stationMap.get(0).size() + 5;
        int steps = 0;
        NavigateNode fatherNode = null;
        NavigateNode currentNode = endNode;
        while (currentNode != null && visited.add(currentNode) && steps++ < maxSteps) {
            currentNode.setIsInflectionPoint(false);
            currentNode.setIsLiftTransferPoint(false);
 
            try {
                JSONObject valueObject = JSON.parseObject(currentNode.getNodeValue());
                if (valueObject != null) {
                    Object isLiftTransfer = valueObject.get("isLiftTransfer");
                    if (isLiftTransfer != null) {
                        String isLiftTransferStr = isLiftTransfer.toString();
                        if ("1".equals(isLiftTransferStr) || "true".equalsIgnoreCase(isLiftTransferStr)) {
                            currentNode.setIsLiftTransferPoint(true);
                        }
                    }
                }
            } catch (Exception ignore) {
            }
 
            HashMap<String, Object> result = searchInflectionPoint(currentNode, fatherNode, currentNode.getFather());
            if (Boolean.parseBoolean(result.get("result").toString())) {
                currentNode.setIsInflectionPoint(true);
                currentNode.setDirection(result.get("direction").toString());
            }
 
            list.add(currentNode);
            fatherNode = currentNode;
            currentNode = currentNode.getFather();
        }
        if (steps >= maxSteps) {
            throw new CoolException("路径回溯超出安全上限,疑似存在父链循环");
        }
 
        Collections.reverse(list);
        for (NavigateNode navigateNode : list) {
            navigateNode.setFather(null);
        }
 
        HashSet<Integer> stationIdSet = new HashSet<>();
        List<NavigateNode> filterList = new ArrayList<>();
        for (NavigateNode navigateNode : list) {
            JSONObject valueObject = JSON.parseObject(navigateNode.getNodeValue());
            if (valueObject.containsKey("rgvCalcFlag")) {
                continue;
            }
            if (stationIdSet.add(valueObject.getInteger("stationId"))) {
                filterList.add(navigateNode);
            }
        }
        return filterList;
    }
 
    public List<NavigateNode> findStationBestPath(List<List<NavigateNode>> allList) {
        if (allList == null || allList.isEmpty()) {
            return new ArrayList<>();
        }
 
        StationPathRuntimeSnapshot runtimeSnapshot = loadStationPathRuntimeSnapshot();
        Map<Integer, StationProtocol> statusMap = runtimeSnapshot.statusMap;
        Set<Integer> outStationIdSet = runtimeSnapshot.outStationIdSet;
        double lenWeightPercent = runtimeSnapshot.lenWeightPercent;
        double congWeightPercent = runtimeSnapshot.congWeightPercent;
        double passOtherOutStationWeightPercent = runtimeSnapshot.passOtherOutStationWeightPercent;
        boolean forceSkipPassOtherOutStation = runtimeSnapshot.forceSkipPassOtherOutStation;
 
        List<List<NavigateNode>> candidates = new ArrayList<>();
        List<Integer> lens = new ArrayList<>();
        List<Integer> tasksList = new ArrayList<>();
        List<Double> congs = new ArrayList<>();
        List<Integer> passOtherOutStationCounts = new ArrayList<>();
        int skippedByPassOtherOutStation = 0;
 
        for (List<NavigateNode> path : allList) {
            if (path == null || path.isEmpty()) {
                continue;
            }
            int len = path.size();
            int tasks = 0;
            HashSet<Integer> stationIdSet = new HashSet<>();
            for (NavigateNode node : path) {
                JSONObject value = null;
                try {
                    value = JSON.parseObject(node.getNodeValue());
                } catch (Exception ignore) {}
                if (value == null) {
                    continue;
                }
                Integer stationId = value.getInteger("stationId");
                if (stationId == null) {
                    continue;
                }
                if (!stationIdSet.add(stationId)) {
                    continue;
                }
                StationProtocol protocol = statusMap.get(stationId);
                if (protocol != null && protocol.getTaskNo() != null && protocol.getTaskNo() > 0) {
                    tasks++;
                }
            }
            double cong = len <= 0 ? 0.0 : (double) tasks / (double) len;
            int passOtherOutStationCount = countPassOtherOutStations(path, outStationIdSet);
            if (forceSkipPassOtherOutStation && passOtherOutStationCount > 0) {
                skippedByPassOtherOutStation++;
                News.info("[WCS Debug] 站点路径候选已跳过,因经过其他出库站点,startStationId={},endStationId={},passOtherOutStationCount={}",
                        extractStationId(path.get(0)),
                        extractStationId(path.get(path.size() - 1)),
                        passOtherOutStationCount);
                continue;
            }
            candidates.add(path);
            lens.add(len);
            tasksList.add(tasks);
            congs.add(cong);
            passOtherOutStationCounts.add(passOtherOutStationCount);
        }
 
        if (candidates.isEmpty()) {
            if (forceSkipPassOtherOutStation && skippedByPassOtherOutStation > 0) {
                News.info("[WCS Debug] 所有站点路径候选均因经过其他出库站点被强制跳过");
                return new ArrayList<>();
            }
            return allList.get(0);
        }
 
        int minLen = Integer.MAX_VALUE;
        int maxLen = Integer.MIN_VALUE;
        double minCong = Double.MAX_VALUE;
        double maxCong = -Double.MAX_VALUE;
        int minPassOtherOutStationCount = Integer.MAX_VALUE;
        int maxPassOtherOutStationCount = Integer.MIN_VALUE;
        for (int i = 0; i < candidates.size(); i++) {
            int l = lens.get(i);
            double c = congs.get(i);
            int p = passOtherOutStationCounts.get(i);
            if (l < minLen) minLen = l;
            if (l > maxLen) maxLen = l;
            if (c < minCong) minCong = c;
            if (c > maxCong) maxCong = c;
            if (p < minPassOtherOutStationCount) minPassOtherOutStationCount = p;
            if (p > maxPassOtherOutStationCount) maxPassOtherOutStationCount = p;
        }
 
        double weightSum = lenWeightPercent + congWeightPercent + passOtherOutStationWeightPercent;
        double lenW = weightSum <= 0 ? 0.5 : lenWeightPercent / weightSum;
        double congW = weightSum <= 0 ? 0.5 : congWeightPercent / weightSum;
        double passOtherOutStationW = weightSum <= 0 ? 0.0 : passOtherOutStationWeightPercent / weightSum;
 
        List<NavigateNode> best = null;
        double bestCost = Double.MAX_VALUE;
        int bestPassOtherOutStationCount = Integer.MAX_VALUE;
        int bestTasks = Integer.MAX_VALUE;
        int bestLen = Integer.MAX_VALUE;
        for (int i = 0; i < candidates.size(); i++) {
            int l = lens.get(i);
            int t = tasksList.get(i);
            double c = congs.get(i);
            int p = passOtherOutStationCounts.get(i);
            //归一化
            double lenNorm = (maxLen - minLen) <= 0 ? 0.0 : (l - minLen) / (double) (maxLen - minLen);
            double congNorm = (maxCong - minCong) <= 0 ? 0.0 : (c - minCong) / (double) (maxCong - minCong);
            double passOtherOutStationNorm = (maxPassOtherOutStationCount - minPassOtherOutStationCount) <= 0
                    ? 0.0
                    : (p - minPassOtherOutStationCount) / (double) (maxPassOtherOutStationCount - minPassOtherOutStationCount);
            //获取权重
            double cost = lenNorm * lenW + congNorm * congW + passOtherOutStationNorm * passOtherOutStationW;
            if (cost < bestCost
                    || (cost == bestCost && p < bestPassOtherOutStationCount)
                    || (cost == bestCost && p == bestPassOtherOutStationCount && t < bestTasks)
                    || (cost == bestCost && p == bestPassOtherOutStationCount && t == bestTasks && l < bestLen)) {
                best = candidates.get(i);
                bestCost = cost;
                bestPassOtherOutStationCount = p;
                bestTasks = t;
                bestLen = l;
            }
        }
 
        if (best == null) {
            return allList.get(0);
        }
        return best;
    }
 
    private Set<Integer> loadAllOutStationIdSet() {
        Set<Integer> outStationIdSet = new HashSet<>();
        try {
            BasDevpService basDevpService = SpringUtils.getBean(BasDevpService.class);
            if (basDevpService == null) {
                return outStationIdSet;
            }
            List<BasDevp> basDevpList = basDevpService.selectList(new EntityWrapper<BasDevp>().eq("status", 1));
            for (BasDevp basDevp : basDevpList) {
                List<StationObjModel> outStationList = basDevp.getOutStationList$();
                for (StationObjModel stationObjModel : outStationList) {
                    if (stationObjModel != null && stationObjModel.getStationId() != null) {
                        outStationIdSet.add(stationObjModel.getStationId());
                    }
                }
            }
        } catch (Exception ignore) {}
        return outStationIdSet;
    }
 
    private int countPassOtherOutStations(List<NavigateNode> path, Set<Integer> outStationIdSet) {
        if (path == null || path.size() < 3 || outStationIdSet == null || outStationIdSet.isEmpty()) {
            return 0;
        }
        Integer startStationId = extractStationId(path.get(0));
        Integer endStationId = extractStationId(path.get(path.size() - 1));
        Set<Integer> hitStationIdSet = new HashSet<>();
        for (int i = 1; i < path.size() - 1; i++) {
            Integer stationId = extractStationId(path.get(i));
            if (stationId == null) {
                continue;
            }
            if (startStationId != null && startStationId.equals(stationId)) {
                continue;
            }
            if (endStationId != null && endStationId.equals(stationId)) {
                continue;
            }
            if (outStationIdSet.contains(stationId)) {
                hitStationIdSet.add(stationId);
            }
        }
        return hitStationIdSet.size();
    }
 
    private Integer extractStationId(NavigateNode node) {
        if (node == null || node.getNodeValue() == null) {
            return null;
        }
        try {
            JSONObject value = JSON.parseObject(node.getNodeValue());
            if (value == null) {
                return null;
            }
            return value.getInteger("stationId");
        } catch (Exception ignore) {}
        return null;
    }
 
    private double loadDoubleConfig(ConfigService configService, String code, double defaultValue) {
        if (configService == null || code == null) {
            return defaultValue;
        }
        Config config = configService.selectOne(new EntityWrapper<Config>().eq("code", code));
        if (config == null || config.getValue() == null) {
            return defaultValue;
        }
        String value = config.getValue().trim();
        if (value.endsWith("%")) {
            value = value.substring(0, value.length() - 1);
        }
        try {
            return Double.parseDouble(value);
        } catch (Exception ignore) {}
        return defaultValue;
    }
 
    private boolean loadBooleanConfig(ConfigService configService, String code, boolean defaultValue) {
        if (configService == null || code == null) {
            return defaultValue;
        }
        Config config = configService.selectOne(new EntityWrapper<Config>().eq("code", code));
        if (config == null || config.getValue() == null) {
            return defaultValue;
        }
        String value = config.getValue().trim();
        if (value.isEmpty()) {
            return defaultValue;
        }
        return "1".equals(value)
                || "true".equalsIgnoreCase(value)
                || "yes".equalsIgnoreCase(value)
                || "y".equalsIgnoreCase(value)
                || "on".equalsIgnoreCase(value);
    }
 
    private StationPathRuntimeSnapshot loadStationPathRuntimeSnapshot() {
        long now = System.currentTimeMillis();
        CachedStationPathRuntimeSnapshot cached = runtimeSnapshotRef.get();
        if (cached != null && now - cached.loadTimeMs < STATION_PATH_RUNTIME_SNAPSHOT_TTL_MS && cached.snapshot != null) {
            return cached.snapshot;
        }
        StationPathRuntimeSnapshot snapshot = buildStationPathRuntimeSnapshot();
        runtimeSnapshotRef.set(new CachedStationPathRuntimeSnapshot(now, snapshot));
        return snapshot;
    }
 
    private StationPathRuntimeSnapshot buildStationPathRuntimeSnapshot() {
        StationPathRuntimeSnapshot snapshot = new StationPathRuntimeSnapshot();
        snapshot.statusMap = loadAllStationStatusMap();
        snapshot.outStationIdSet = loadAllOutStationIdSet();
 
        try {
            ConfigService configService = SpringUtils.getBean(ConfigService.class);
            if (configService != null) {
                snapshot.lenWeightPercent = loadDoubleConfig(configService, CFG_STATION_PATH_LEN_WEIGHT_PERCENT, snapshot.lenWeightPercent);
                snapshot.congWeightPercent = loadDoubleConfig(configService, CFG_STATION_PATH_CONG_WEIGHT_PERCENT, snapshot.congWeightPercent);
                snapshot.passOtherOutStationWeightPercent = loadDoubleConfig(configService, CFG_STATION_PATH_PASS_OTHER_OUT_STATION_WEIGHT_PERCENT, snapshot.passOtherOutStationWeightPercent);
                snapshot.forceSkipPassOtherOutStation = loadBooleanConfig(configService, CFG_STATION_PATH_PASS_OTHER_OUT_STATION_FORCE_SKIP, false);
            }
        } catch (Exception ignore) {
        }
        return snapshot;
    }
 
    private Map<Integer, StationProtocol> loadAllStationStatusMap() {
        Map<Integer, StationProtocol> statusMap = new HashMap<>();
        try {
            DeviceConfigService deviceConfigService = SpringUtils.getBean(DeviceConfigService.class);
            if (deviceConfigService == null) {
                return statusMap;
            }
            List<DeviceConfig> devpList = deviceConfigService.selectList(new EntityWrapper<DeviceConfig>()
                    .eq("device_type", String.valueOf(SlaveType.Devp)));
            for (DeviceConfig deviceConfig : devpList) {
                StationThread stationThread = (StationThread) SlaveConnection.get(SlaveType.Devp, deviceConfig.getDeviceNo());
                if (stationThread == null) {
                    continue;
                }
                Map<Integer, StationProtocol> m = stationThread.getStatusMap();
                if (m != null && !m.isEmpty()) {
                    statusMap.putAll(m);
                }
            }
        } catch (Exception ignore) {
        }
        return statusMap;
    }
 
    //判断当前节点到下一个节点是否为拐点
    public HashMap<String,Object> searchInflectionPoint(NavigateNode currentNode, NavigateNode fatherNode, NavigateNode nextNode) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("result", false);//是否为拐点,true:拐点,false:直线
        // 第一个点或直线点
        if (fatherNode == null || nextNode == null || nextNode.getX() == fatherNode.getX() || nextNode.getY() == fatherNode.getY()) {
            return map;//不是拐点直接返回
        }
 
        //拐点方向
        String direction = calcDirection(currentNode, fatherNode);
 
        map.put("result", true);//拐点
        map.put("direction", direction);//拐点方向(从当前节点视角看的方向)
        return map;
    }
 
    /**
     * 计算方向
     */
    public String calcDirection(NavigateNode currentNode, NavigateNode fatherNode) {
        //拐点方向
        String direction = "";
        // 普通拐点
        //计算拐点方向
        if (fatherNode.getX() != currentNode.getX()) {
            //x轴数据有差异,判断x轴方向
            //当前节点X - 父节点X
            if (currentNode.getX() - fatherNode.getX() > 0) {
                //大于0,方向top
                direction = "top";
            }else {
                //小于0,方向bottom
                direction = "bottom";
            }
        }
 
        if (fatherNode.getY() != currentNode.getY()) {
            //y轴数据有差异,判断y轴方向
            //当前节点Y - 父节点Y
            if (currentNode.getY() - fatherNode.getY() > 0) {
                //大于0,方向left
                direction = "left";
            }else {
                //小于0,方向right
                direction = "right";
            }
        }
 
        return direction;
    }
 
    private static class StationPathRuntimeSnapshot {
        private Map<Integer, StationProtocol> statusMap = new HashMap<>();
        private Set<Integer> outStationIdSet = new HashSet<>();
        private double lenWeightPercent = 50.0;
        private double congWeightPercent = 50.0;
        private double passOtherOutStationWeightPercent = 100.0;
        private boolean forceSkipPassOtherOutStation = false;
    }
 
    private static class CachedStationPathRuntimeSnapshot {
        private final long loadTimeMs;
        private final StationPathRuntimeSnapshot snapshot;
 
        private CachedStationPathRuntimeSnapshot(long loadTimeMs, StationPathRuntimeSnapshot snapshot) {
            this.loadTimeMs = loadTimeMs;
            this.snapshot = snapshot;
        }
    }
}