#
luxiaotao1123
2024-12-18 613b59f94870adb25b6dd1e8a1aba8cbb670288e
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
package com.zy.acs.manager.core.service;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zy.acs.common.constant.RedisConstant;
import com.zy.acs.common.utils.RedisSupport;
import com.zy.acs.common.utils.Utils;
import com.zy.acs.framework.common.Cools;
import com.zy.acs.manager.common.utils.MapDataUtils;
import com.zy.acs.manager.core.constant.MapDataConstant;
import com.zy.acs.manager.core.domain.Lane;
import com.zy.acs.manager.core.service.astart.*;
import com.zy.acs.manager.core.service.astart.domain.DynamicNode;
import com.zy.acs.manager.core.utils.RouteGenerator;
import com.zy.acs.manager.manager.entity.Code;
import com.zy.acs.manager.manager.entity.Jam;
import com.zy.acs.manager.manager.entity.Route;
import com.zy.acs.manager.manager.entity.Segment;
import com.zy.acs.manager.manager.enums.JamStateType;
import com.zy.acs.manager.manager.service.*;
import com.zy.acs.manager.system.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * Created by vincent on 7/25/2024
 */
@Slf4j
@Service
public class RetreatNavigateService {
 
    private final RedisSupport redis = RedisSupport.defaultRedisSupport;
 
    public static final int WEIGHT_CALC_FACTOR = 10000;
 
    @Autowired
    private CodeService codeService;
    @Autowired
    private RouteService routeService;
    @Autowired
    private MapDataDispatcher mapDataDispatcher;
    @Autowired
    private MapService mapService;
    @Autowired
    private AgvService agvService;
    @Autowired
    private AgvModelService agvModelService;
    @Autowired
    private LaneService laneService;
    @Autowired
    private ConfigService configService;
    @Autowired
    private SegmentService segmentService;
    @Autowired
    private JamService jamService;
 
    /**
     * avoidPathList ===>>  [ minor vehicle ] [wave] [ curr vehicle ] [ code2 ] [ code3 ] ......
     **/
//    @SuppressWarnings("all")
    public RetreatNavigateNode execute(String agvNo, RetreatNavigateNode start, List<String> avoidPathList, String sponsor, Jam jam) {
        if (Cools.isEmpty(avoidPathList)) {
            return null;
        }
        Integer lev = null;
        Integer maxAgvCountInLane = configService.getVal("maxAgvCountInLane", Integer.class);
 
        String breakPoint = avoidPathList.stream().findFirst().orElse(null);
        List<String> blackList = Utils.singletonList(sponsor);
 
        Double avoidDistance = MapDataUtils.getVehicleWaveSafeDistance(agvModelService.getById(agvService.selectByUuid(sponsor).getAgvModel()).getDiameter()
                , MapDataConstant.MAX_DISTANCE_BETWEEN_ADJACENT_AGV_FACTOR);
        List<String> avoidPathListWave = mapService.getWaveScopeByCodeList(lev, avoidPathList, avoidDistance);
 
        DynamicNode[][] dynamicMatrix = mapDataDispatcher.getDynamicMatrix(lev);
        String[][] waveMatrix = mapDataDispatcher.getWaveMatrix(lev);
 
 
        RetreatNavigateNode finialNode = null;
 
        PriorityQueue<RetreatNavigateNode> openQueue = new PriorityQueue<>();
        Set<RetreatNavigateNode> existNodes = new HashSet<>();
 
        openQueue.add(start);
        existNodes.add(start);
        boolean phaseSecond = true;
 
        while (!openQueue.isEmpty() && null == finialNode) {
 
            RetreatNavigateNode currentNode = openQueue.poll();
 
            List<RetreatNavigateNode> enableNodes = new ArrayList<>();
 
            ArrayList<RetreatNavigateNode> neighborNodes = this.getNeighborNodes(currentNode, existNodes);
            boolean pointOfTurn = neighborNodes.size() >= 2;
            label: for (RetreatNavigateNode node : neighborNodes) {
                if (node.getCodeData().equals(breakPoint)) { continue; }
                Code code = codeService.selectByData(node.getCodeData());
 
                int weight = 0;
 
                // wave
                String waveNode = waveMatrix[node.getX()][node.getY()];
                assert !waveNode.equals(WaveNodeType.DISABLE.val);
                if (!waveNode.equals(WaveNodeType.ENABLE.val)) {
                    List<String> waveNodeList = MapDataUtils.parseWaveNode(waveNode);
                    List<String> otherWaveList = MapDataUtils.hasOtherWave(waveNodeList, agvNo);
                    for (String otherWave : otherWaveList) {
                        if (!Cools.isEmpty(blackList) && blackList.contains(otherWave)) {
                            continue label;
                        }
                        if (1 < mapDataDispatcher.queryCodeListFromDynamicNode(lev, otherWave).size()) {
                            phaseSecond = false;    // there is a running way
                            continue label;
                        } else {
                            weight += WEIGHT_CALC_FACTOR;
                        }
                    }
                }
 
                // lane
                if (pointOfTurn) {
                    Lane lane = laneService.search(node.getCodeData());
                    if (null != lane) {
                        Set<String> lanVehicleSet = new HashSet<>();
 
                        for (String laneCodeData : lane.getCodes()) {
                            // overlap with sponsor
                            if (avoidPathList.contains(laneCodeData)) {
                                lanVehicleSet.add(sponsor);
                            }
 
                            int[] laneCodeMatrixIdx = mapDataDispatcher.getCodeMatrixIdx(null, laneCodeData);
                            // scan dynamicMatrix or WaveMatrix
                            DynamicNode laneDynamicNode = dynamicMatrix[laneCodeMatrixIdx[0]][laneCodeMatrixIdx[1]];
                            String laneVehicle = laneDynamicNode.getVehicle();
                            assert !laneVehicle.equals(DynamicNodeType.BLOCK.val);
                            if (!laneVehicle.equals(DynamicNodeType.ACCESS.val)) {
                                if (!laneVehicle.equals(agvNo)) {
                                    lanVehicleSet.add(laneVehicle);
//                                    redis.setObject(RedisConstant.AGV_TO_STANDBY_FLAG, laneVehicle, true, 30);
                                }
                            }
                        }
 
                        if (lanVehicleSet.size() + 1 > maxAgvCountInLane) {
                            phaseSecond = false;    // there is a running way
                            continue;
                        }
                        if (lanVehicleSet.contains(sponsor)) {
                            weight += WEIGHT_CALC_FACTOR * 2;
                        }
                    }
                }
 
                // judge whether the node has already been marked as a retreat node?
                // This is a very troublesome matter, if the node be repeatedly mark as a retreat node
                List<Segment> runningSegments = segmentService.getRunningByEndCode(code.getId());
                for (Segment runningSeg : runningSegments) {
                    if (0 < jamService.count(new LambdaQueryWrapper<Jam>()
                            .eq(Jam::getAvoSeg, runningSeg.getId())
                            .ne(Jam::getState, JamStateType.DEPRECATED.toString()))) {
                        weight += WEIGHT_CALC_FACTOR * 3;
                    } else {
                        weight += WEIGHT_CALC_FACTOR;
                    }
                }
 
                // enable
                if (!avoidPathListWave.contains(node.getCodeData())) {
                    enableNodes.add(node);
                }
 
                int gCost = calcNodeCost(currentNode, node);
 
                //进行计算对 G, F, H 等值
                node.setLastDistance(gCost);
                node.initNode(currentNode, weight);
 
                openQueue.add(node);
                existNodes.add(node);
 
            }
 
            if (!Cools.isEmpty(enableNodes)) {
                Collections.sort(enableNodes);
                finialNode = enableNodes.stream().findFirst().orElse(null);
                jam.setCycleAvo(0);
            }
        }
 
 
        if (null == finialNode && phaseSecond) {
//            assert openQueue.size() == 0;
 
            existNodes.clear();
            openQueue.add(start);
            existNodes.add(start);
 
            RetreatNavigateNode availablePointOfTurn = null;
            List<String> availablePointWaveScopeOfTurn = new ArrayList<>();
            int actualLanesOfTurn = 0;
            int filterPointOfTurnTimes = 0;
 
            while (!openQueue.isEmpty() && null == finialNode) {
 
                RetreatNavigateNode currentNode = openQueue.poll();
                List<RetreatNavigateNode> enableNodes = new ArrayList<>();
 
                ArrayList<RetreatNavigateNode> neighborNodes = this.getNeighborNodes(currentNode, existNodes);
 
                // 第一步:获取有效转弯点
                if (null == availablePointOfTurn) {
                    // 计算是否为可用转弯点
                    if (neighborNodes.size() >= 2 && !isSame(start, currentNode)) {
                        filterPointOfTurnTimes ++;
                        if (filterPointOfTurnTimes > 2) { break; }
 
                        for (RetreatNavigateNode node : neighborNodes) {
                            // lane
                            Lane lane = laneService.search(node.getCodeData());
                            if (null != lane) {
                                Set<String> lanVehicleSet = new HashSet<>();
 
                                for (String laneCodeData : lane.getCodes()) {
                                    int[] laneCodeMatrixIdx = mapDataDispatcher.getCodeMatrixIdx(null, laneCodeData);
                                    // scan dynamicMatrix or WaveMatrix
                                    DynamicNode laneDynamicNode = dynamicMatrix[laneCodeMatrixIdx[0]][laneCodeMatrixIdx[1]];
                                    String laneVehicle = laneDynamicNode.getVehicle();
                                    assert !laneVehicle.equals(DynamicNodeType.BLOCK.val);
                                    if (!laneVehicle.equals(DynamicNodeType.ACCESS.val)) {
                                        if (!laneVehicle.equals(agvNo)) {
                                            lanVehicleSet.add(laneVehicle);
//                                            redis.setObject(RedisConstant.AGV_TO_STANDBY_FLAG, laneVehicle, true, 30);
                                        }
                                    }
                                }
 
                                if (lanVehicleSet.size() + 1 > maxAgvCountInLane) {
                                    continue;
                                }
                            }
 
                            actualLanesOfTurn ++;
                        }
 
                        // 有两条以上可走巷道,则视为有效转弯点
                        if (actualLanesOfTurn >= 2) {
                            availablePointOfTurn = currentNode;
                            availablePointWaveScopeOfTurn = mapService.getWaveScopeByCode(lev, availablePointOfTurn.getCodeData(), avoidDistance)
                                    .stream().map(NavigateNode::getCodeData).distinct().collect(Collectors.toList());
                        } else {
                            actualLanesOfTurn = 0;
                        }
                    }
                }
 
                // 延伸转弯点巷道
                label: for (RetreatNavigateNode node : neighborNodes) {
                    int weight = 0;
 
                    // wave
                    String waveNode = waveMatrix[node.getX()][node.getY()];
                    assert !waveNode.equals(WaveNodeType.DISABLE.val);
                    if (!waveNode.equals(WaveNodeType.ENABLE.val)) {
                        List<String> waveNodeList = MapDataUtils.parseWaveNode(waveNode);
                        List<String> otherWaveList = MapDataUtils.hasOtherWave(waveNodeList, agvNo);
                        for (String otherWave : otherWaveList) {
                            if (!Cools.isEmpty(blackList) && blackList.contains(otherWave)) {
                                continue;
                            }
                            if (1 < mapDataDispatcher.queryCodeListFromDynamicNode(lev, otherWave).size()) {
 
                                if (null != availablePointOfTurn && actualLanesOfTurn > 0) {
                                    actualLanesOfTurn --;
                                }
                                continue label;
                            } else {
                                weight += WEIGHT_CALC_FACTOR;
                            }
                        }
                    }
 
                    if (null != availablePointOfTurn) {
                        if (!availablePointWaveScopeOfTurn.contains(node.getCodeData())) {
                            enableNodes.add(node);
                        }
                    }
 
                    node.setLastDistance(calcNodeCost(currentNode, node));
                    node.initNode(currentNode, weight);
 
                    openQueue.add(node);
                    existNodes.add(node);
                }
 
                if (actualLanesOfTurn < 2) {
                    availablePointOfTurn = null;
                    availablePointWaveScopeOfTurn = new ArrayList<>();
                    actualLanesOfTurn = 0;
                } else {
                    if (!Cools.isEmpty(enableNodes)) {
                        Collections.sort(enableNodes);
                        finialNode = enableNodes.stream().findFirst().orElse(null);
                        jam.setCycleAvo(1);
                    }
                }
 
            }
 
        }
 
        return finialNode;
    }
 
    // 获取四周节点
    private ArrayList<RetreatNavigateNode> getNeighborNodes(RetreatNavigateNode currentNode, Set<RetreatNavigateNode> existNodes) {
 
        int x = currentNode.getX();
        int y = currentNode.getY();
 
        ArrayList<RetreatNavigateNode> neighbourNodes = new ArrayList<>();
 
        RetreatNavigateNode rightNode = extendNeighborNodes(currentNode, new RetreatNavigateNode(x, y + 1), existNodes, null, null);
        if (null != rightNode) {
            neighbourNodes.add(rightNode);
        }
 
        RetreatNavigateNode leftNode = extendNeighborNodes(currentNode, new RetreatNavigateNode(x, y - 1), existNodes, null, null);
        if (null != leftNode) {
            neighbourNodes.add(leftNode);
        }
 
        RetreatNavigateNode topNode = extendNeighborNodes(currentNode, new RetreatNavigateNode(x - 1, y), existNodes, null, null);
        if (null != topNode) {
            neighbourNodes.add(topNode);
        }
 
        RetreatNavigateNode bottomNode = extendNeighborNodes(currentNode, new RetreatNavigateNode(x + 1, y), existNodes, null, null);
        if (null != bottomNode) {
            neighbourNodes.add(bottomNode);
        }
 
        return neighbourNodes;
    }
 
    private RetreatNavigateNode extendNeighborNodes(RetreatNavigateNode currentNode, RetreatNavigateNode extendNode, Set<RetreatNavigateNode> existNodes, Integer dx, Integer dy) {
        RetreatNavigateNode nextNode;
 
        if (null == dx || null == dy) {
            dx = extendNode.getX() - currentNode.getX();
            dy = extendNode.getY() - currentNode.getY();
            nextNode = extendNode;
        } else {
            nextNode = new RetreatNavigateNode(extendNode.getX() + dx, extendNode.getY() + dy);
        }
 
        int x = nextNode.getX();
        int y = nextNode.getY();
 
        // 数组越界
        int[][] mapMatrix = mapDataDispatcher.getMapMatrix(null, null);
        if (x < 0 || x >= mapMatrix.length
                || y < 0 || y >= mapMatrix[0].length) {
            return null;
        }
 
        if (mapMatrix[x][y] == MapNodeType.DISABLE.val)  {
 
            return extendNeighborNodes(currentNode, nextNode, existNodes, dx, dy);
 
        } else {
            if (existNodes.contains(nextNode)) {
                return null;
            }
 
            // 节点是否可用
            if (mapMatrix[x][y] != MapNodeType.ENABLE.val) {
                return null;
            }
 
            String[][] codeMatrix = mapDataDispatcher.getCodeMatrix(null);
            String currentNodeCodeData = codeMatrix[currentNode.getX()][currentNode.getY()];
            String nextNodeCodeData = codeMatrix[nextNode.getX()][nextNode.getY()];
            nextNode.setCodeData(nextNodeCodeData);
 
            // 判断通过性
            String routeKey = RouteGenerator.generateRouteKey(currentNodeCodeData, nextNodeCodeData);
            Object routeVal = redis.getMap(RedisConstant.AGV_MAP_ROUTE_HASH_FLAG, routeKey);
            if (routeVal == null || !(Boolean) routeVal) {
                return null;
            }
        }
 
        return nextNode;
    }
 
    private boolean isExist(RetreatNavigateNode node, List<RetreatNavigateNode> existNodes) {
        for (RetreatNavigateNode existNode : existNodes) {
            if (this.isSame(node, existNode)) {
                return true;
            }
        }
        return false;
    }
 
    private boolean isSame(RetreatNavigateNode o1, RetreatNavigateNode o2) {
        if (Cools.isEmpty(o1, o2)) {
            return false;
        }
        return o1.getX() == o2.getX() && o1.getY() == o2.getY();
    }
 
    private int calcNodeCost(RetreatNavigateNode node1, RetreatNavigateNode node2) {
 
        return Math.abs(node2.getX() - node1.getX()) + Math.abs(node2.getY() - node1.getY());
    }
 
}