#
luxiaotao1123
2025-01-08 aa6f20d98b5d8e18ae56f9562a78d403a5417b48
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
package com.zy.acs.manager.core.service;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zy.acs.common.utils.Utils;
import com.zy.acs.framework.common.Cools;
import com.zy.acs.manager.common.config.RedisProperties;
import com.zy.acs.manager.common.utils.MapDataUtils;
import com.zy.acs.manager.core.constant.MapDataConstant;
import com.zy.acs.manager.core.service.astart.DynamicNodeType;
import com.zy.acs.manager.core.service.astart.MapDataDispatcher;
import com.zy.acs.manager.core.service.astart.NavigateNode;
import com.zy.acs.manager.core.service.astart.domain.DynamicNode;
import com.zy.acs.manager.manager.entity.Agv;
import com.zy.acs.manager.manager.entity.AgvDetail;
import com.zy.acs.manager.manager.entity.AgvModel;
import com.zy.acs.manager.manager.entity.Code;
import com.zy.acs.manager.manager.enums.AgvModelType;
import com.zy.acs.manager.manager.service.AgvDetailService;
import com.zy.acs.manager.manager.service.AgvModelService;
import com.zy.acs.manager.manager.service.AgvService;
import com.zy.acs.manager.manager.service.CodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
 
/**
 * Created by vincent on 8/6/2024
 */
@Slf4j
@Component
public class AvoidWaveCalculator {
 
    private static final ReentrantLock lock = new ReentrantLock(Boolean.TRUE);
 
    private static final int LOCK_TIMEOUT = 5;
 
    private ExecutorService singleThreadExecutor;
 
    private File pythonFile = null;
 
    @Autowired
    private MapDataDispatcher mapDataDispatcher;
    @Autowired
    private AgvService agvService;
    @Autowired
    private AgvDetailService agvDetailService;
    @Autowired
    private AgvModelService agvModelService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private MapService mapService;
    @Autowired
    private RedisProperties redisProperties;
 
    @PostConstruct
    @SuppressWarnings("all")
    public void execute() {
        this.singleThreadExecutor = Executors.newSingleThreadExecutor();
        this.singleThreadExecutor.execute(() -> {
 
            try { Thread.sleep(200); } catch (InterruptedException ignore) {}
 
            this.calcDynamicNodeWhenBoot();
 
//            while (!Thread.currentThread().isInterrupted()) {
//
//                this.calcWaveScope();
//
//                try { Thread.sleep(500); } catch (InterruptedException ignore) {}
//            }
 
        });
    }
 
 
    public boolean calcWaveScope() {
        Integer lev = MapDataDispatcher.MAP_DEFAULT_LEV;
        boolean lockAcquired = false;
 
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
 
        try {
            if (!(lockAcquired = lock.tryLock(LOCK_TIMEOUT, TimeUnit.SECONDS))) {
                log.warn("AvoidWaveCalculator execute fail, cause can not acquire lock ...");
                return false;
            }
 
//            return this.calcWaveScopeByPython(lev);
            return this.calcWaveScopeByJava(lev);
 
        } catch (Exception e) {
 
            log.error(this.getClass().getSimpleName(), e);
            return false;
        } finally {
 
            if (lockAcquired) {
                lock.unlock();
            }
 
            stopWatch.stop();
            if (stopWatch.getTime() > 0) {
                log.info("滤波函数花费时间为:{}毫秒......", stopWatch.getTime());
            }
        }
    }
 
    private boolean calcWaveScopeByPython(Integer lev) throws Exception {
        // python
        AgvModel agvModel = agvModelService.selectByType(AgvModelType.CTU_BOX_TRANSPORT_AGV.toString());    // can be optimized
        Double avoidDistance = MapDataUtils.getVehicleWaveSafeDistance(agvModel.getDiameter(), MapDataConstant.MAX_DISTANCE_BETWEEN_ADJACENT_AGV_FACTOR);
 
        if (null == pythonFile) {
            pythonFile = loadPythonFile();
        }
 
        ProcessBuilder processBuilder = new ProcessBuilder(
                "python" // 或者 "python3" 取决于系统配置
                , pythonFile.getAbsolutePath()
                , String.valueOf(avoidDistance)
                , redisProperties.getHost()
                , redisProperties.getPassword()
                , String.valueOf(redisProperties.getPort())
                , String.valueOf(redisProperties.getIndex())
        );
 
        processBuilder.redirectErrorStream(true);
 
        Process process = processBuilder.start();
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        StringBuilder builder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
 
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            log.error("Python script exited with error code: {}", exitCode);
            log.error("python error:{}", builder.toString());
            return false;
        }
        reader.close();
 
        if (builder.length() <= 0) {
            return false;
        }
 
        String result = builder.toString();
 
        if (Cools.isEmpty(result)) {
            return false;
        }
        if (!"1".equals(result)) {
            log.error("Failed to call python");
            return false;
        }
 
        return true;
    }
 
    private boolean calcWaveScopeByJava(Integer lev) throws Exception {
        AgvModel agvModel = agvModelService.selectByType(AgvModelType.CTU_BOX_TRANSPORT_AGV.toString());    // can be optimized
        Double avoidDistance = MapDataUtils.getVehicleWaveSafeDistance(agvModel.getDiameter(), MapDataConstant.MAX_DISTANCE_BETWEEN_ADJACENT_AGV_FACTOR);
 
        // java
        String[][] codeMatrix = mapDataDispatcher.getCodeMatrix(lev);
        String[][] waveMatrix = mapDataDispatcher.initWaveMatrix(lev);
 
        // lock path
        DynamicNode[][] dynamicMatrix = mapDataDispatcher.getDynamicMatrix(lev);
        for (int i = 0; i < dynamicMatrix.length; i++) {
            for (int j = 0; j < dynamicMatrix[i].length; j++) {
                DynamicNode dynamicNode = dynamicMatrix[i][j];
                String vehicle = dynamicNode.getVehicle();
                if (!DynamicNodeType.ACCESS.val.equals(vehicle) && !DynamicNodeType.BLOCK.val.equals(vehicle)) {
 
                    List<NavigateNode> includeList = mapService.getWaveScopeByCode(lev, codeMatrix[i][j], avoidDistance);
 
                    for (NavigateNode navigateNode : includeList) {
                        String waveNode = waveMatrix[navigateNode.getX()][navigateNode.getY()]; // overlay
                        waveMatrix[navigateNode.getX()][navigateNode.getY()] = MapDataUtils.generateWaveNode(waveNode, vehicle);
                    }
                }
            }
        }
 
//            mapDataDispatcher.printMatrix(waveMatrix);
        mapDataDispatcher.setWaveMatrix(lev, waveMatrix);
 
        return true;
    }
 
    private File loadPythonFile() {
        File scriptFile = null;
        try {
            Resource resource = new ClassPathResource("agv.py");
 
            InputStream is = resource.getInputStream();
            scriptFile = File.createTempFile("agv", ".py");
            scriptFile.deleteOnExit();
 
            Files.copy(is, scriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
 
            boolean executable = scriptFile.setExecutable(true);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return scriptFile;
    }
 
    public void syncWaveBySingleVeh(String agvNo, String codeData) {
        if (Cools.isEmpty(agvNo, codeData)) {
            return;
        }
 
        boolean lockAcquired = false;
        Integer lev = MapDataDispatcher.MAP_DEFAULT_LEV;
 
        try {
            if (!(lockAcquired = lock.tryLock(LOCK_TIMEOUT, TimeUnit.SECONDS))) {
                log.warn("AvoidWaveCalculator syncWaveBySingleVeh fail, cause can not acquire lock ...");
                return;
            }
 
            Agv agv = agvService.selectByUuid(agvNo);
            AgvModel agvModel = agvModelService.getByAgvNo(agvNo);
            Double avoidDistance = MapDataUtils.getVehicleWaveSafeDistance(agvModel.getDiameter(), MapDataConstant.MAX_DISTANCE_BETWEEN_ADJACENT_AGV_FACTOR);
 
            String[][] waveMatrix = mapDataDispatcher.getWaveMatrix(lev);
 
            List<NavigateNode> includeList = mapService.getWaveScopeByCode(lev, codeData, avoidDistance);
 
            for (NavigateNode navigateNode : includeList) {
                String waveNode = waveMatrix[navigateNode.getX()][navigateNode.getY()];
                waveMatrix[navigateNode.getX()][navigateNode.getY()] = MapDataUtils.generateWaveNode(waveNode, agv.getUuid());
            }
 
            mapDataDispatcher.setWaveMatrix(lev, waveMatrix);
 
        } catch (Exception e) {
            log.error("AvoidWaveCalculator.syncWaveBySingleVeh fail", e);
        } finally {
 
            if (lockAcquired) {
                lock.unlock();
            }
        }
    }
 
    public void calcDynamicNodeWhenBoot() {
        List<Agv> agvList = agvService.list(new LambdaQueryWrapper<>());
        DynamicNode[][] dynamicMatrix = mapDataDispatcher.getDynamicMatrix(null);
 
        for (Agv agv : agvList) {
            calcDynamicNodeByVehicle(agv, dynamicMatrix);
        }
    }
 
    public void calcDynamicNodeByVehicle(Agv agv, DynamicNode[][] dynamicMatrix) {
        if (null == dynamicMatrix) {
            dynamicMatrix = mapDataDispatcher.getDynamicMatrix(null);
        }
        AgvDetail agvDetail = agvDetailService.selectByAgvId(agv.getId());
        if (null == agvDetail) {
            return;
        }
        if (agvDetail.getPos() == null) {
            return;
        }
        Long recentCode = agvDetail.getRecentCode();
        if (null == recentCode) {
            return;
        }
        Code code = codeService.getById(recentCode);
        if (null == code) {
            return;
        }
        int[] codeMatrixIdx = mapDataDispatcher.getCodeMatrixIdx(null, code.getData());
        DynamicNode dynamicNode = dynamicMatrix[codeMatrixIdx[0]][codeMatrixIdx[1]];
        String vehicle = dynamicNode.getVehicle();
        if (vehicle.equals(DynamicNodeType.ACCESS.val)) {
            mapDataDispatcher.modifyDynamicMatrix(null, Utils.singletonList(codeMatrixIdx), agv.getUuid());
        }
    }
 
    @PreDestroy
    public void destroy() {
        this.singleThreadExecutor.shutdownNow();
    }
 
}