Junjie
7 小时以前 9ed9cd2e6f619c84732ae6715699b160c404684c
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
package com.zy.core.thread.impl.station;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.core.common.Cools;
import com.core.common.SpringUtils;
import com.zy.asrs.domain.vo.StationTaskTraceSegmentVo;
import com.zy.asrs.entity.DeviceConfig;
import com.zy.common.utils.RedisUtil;
import com.zy.core.cache.SlaveConnection;
import com.zy.core.enums.RedisKeyType;
import com.zy.core.enums.SlaveType;
import com.zy.core.enums.StationCommandType;
import com.zy.core.model.CommandResponse;
import com.zy.core.model.command.StationCommand;
import com.zy.core.model.protocol.StationProtocol;
import com.zy.core.move.StationMoveCoordinator;
import com.zy.core.trace.StationTaskTraceRegistry;
import com.zy.system.entity.Config;
import com.zy.system.service.ConfigService;
 
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
 
public class StationSegmentExecutor {
 
    private static final String CFG_STATION_COMMAND_SEGMENT_ADVANCE_RATIO = "stationCommandSegmentAdvanceRatio";
    private static final double DEFAULT_STATION_COMMAND_SEGMENT_ADVANCE_RATIO = 0.3d;
    private static final long CURRENT_STATION_TIMEOUT_MS = 1000L * 60L;
 
    private final DeviceConfig deviceConfig;
    private final RedisUtil redisUtil;
    private final Function<StationCommand, CommandResponse> commandSender;
    private final StationSegmentPlanner segmentPlanner = new StationSegmentPlanner();
 
    public StationSegmentExecutor(DeviceConfig deviceConfig,
                                  RedisUtil redisUtil,
                                  Function<StationCommand, CommandResponse> commandSender) {
        this.deviceConfig = deviceConfig;
        this.redisUtil = redisUtil;
        this.commandSender = commandSender;
    }
 
    public void execute(StationCommand original) {
        if (original == null) {
            return;
        }
        if (original.getCommandType() != StationCommandType.MOVE) {
            commandSender.apply(original);
            return;
        }
 
        StationSegmentExecutionPlan localPlan = segmentPlanner.buildPlan(original);
        if (localPlan.getSegmentCommands().isEmpty()) {
            return;
        }
 
        StationTaskTraceRegistry traceRegistry = SpringUtils.getBean(StationTaskTraceRegistry.class);
        StationTaskTraceRegistry.TraceRegistration traceRegistration = traceRegistry == null
                ? new StationTaskTraceRegistry.TraceRegistration()
                : traceRegistry.registerPlan(original.getTaskNo(), deviceConfig.getThreadImpl(),
                original.getStationId(), original.getStationId(), original.getTargetStaNo(),
                localPlan.getFullPathStationIds(), buildTraceSegments(localPlan.getSegmentCommands()));
        int traceVersion = traceRegistration.getTraceVersion() == null ? 1 : traceRegistration.getTraceVersion();
        int pathOffset = traceRegistration.getPathOffset() == null ? 0 : traceRegistration.getPathOffset();
        bindCommands(localPlan.getSegmentCommands(), traceVersion, pathOffset, original.getRouteVersion());
        List<Integer> effectiveFullPath = traceRegistration.getFullPathStationIds() == null
                || traceRegistration.getFullPathStationIds().isEmpty()
                ? copyIntegerList(localPlan.getFullPathStationIds())
                : copyIntegerList(traceRegistration.getFullPathStationIds());
 
        StationCommand firstCommand = localPlan.getSegmentCommands().get(0);
        if (!sendSegmentWithRetry(firstCommand, traceRegistry, traceVersion, null)) {
            return;
        }
        if (traceRegistry != null) {
            traceRegistry.markSegmentIssued(original.getTaskNo(), traceVersion, firstCommand,
                    "FIRST_SEGMENT_SENT", "输送任务首段下发成功", buildSegmentDetails(firstCommand));
        }
 
        long lastSeenAt = System.currentTimeMillis();
        int segCursor = 0;
        Integer lastCurrentStationId = null;
        boolean firstRun = true;
        while (true) {
            try {
                if (!isRouteActive(original.getTaskNo(), original.getRouteVersion())) {
                    if (traceRegistry != null) {
                        traceRegistry.markCancelled(original.getTaskNo(), traceVersion, lastCurrentStationId,
                                buildDetails("reason", "route_version_replaced", "routeVersion", original.getRouteVersion()));
                    }
                    markCancelled(original.getTaskNo(), original.getRouteVersion(), lastCurrentStationId, "route_version_replaced");
                    break;
                }
 
                Object cancel = redisUtil.get(RedisKeyType.DEVICE_STATION_MOVE_RESET.key + original.getTaskNo());
                if (cancel != null) {
                    if (traceRegistry != null) {
                        traceRegistry.markCancelled(original.getTaskNo(), traceVersion, lastCurrentStationId,
                                buildDetails("reason", "redis_cancel_signal", "routeVersion", original.getRouteVersion()));
                    }
                    markCancelled(original.getTaskNo(), original.getRouteVersion(), lastCurrentStationId, "redis_cancel_signal");
                    break;
                }
 
                StationProtocol currentStation = findCurrentStationByTask(original.getTaskNo());
                if (currentStation == null) {
                    if (System.currentTimeMillis() - lastSeenAt > CURRENT_STATION_TIMEOUT_MS) {
                        if (traceRegistry != null) {
                            traceRegistry.markTimeout(original.getTaskNo(), traceVersion, lastCurrentStationId,
                                    buildDetails("timeoutMs", CURRENT_STATION_TIMEOUT_MS, "routeVersion", original.getRouteVersion()));
                        }
                        markTimeout(original.getTaskNo(), original.getRouteVersion(), lastCurrentStationId);
                        break;
                    }
                    Thread.sleep(500L);
                    continue;
                }
 
                lastSeenAt = System.currentTimeMillis();
                Integer previousCurrentStationId = lastCurrentStationId;
                updateCurrentStation(original.getTaskNo(), original.getRouteVersion(), currentStation.getStationId());
                if (traceRegistry != null) {
                    traceRegistry.updateProgress(original.getTaskNo(), traceVersion, currentStation.getStationId(),
                            equalsInteger(previousCurrentStationId, currentStation.getStationId()) ? null : "CURRENT_STATION_CHANGE",
                            "输送任务当前位置已更新",
                            buildDetails("stationId", currentStation.getStationId(), "routeVersion", original.getRouteVersion()));
                }
                lastCurrentStationId = currentStation.getStationId();
                if (!firstRun && currentStation.isRunBlock()) {
                    if (traceRegistry != null) {
                        traceRegistry.markBlocked(original.getTaskNo(), traceVersion, currentStation.getStationId(),
                                buildDetails("blockedStationId", currentStation.getStationId(), "routeVersion", original.getRouteVersion()));
                    }
                    markBlocked(original.getTaskNo(), original.getRouteVersion(), currentStation.getStationId());
                    break;
                }
 
                int currentIndex = effectiveFullPath.indexOf(currentStation.getStationId());
                if (currentIndex < 0) {
                    Thread.sleep(500L);
                    firstRun = false;
                    continue;
                }
 
                int remaining = effectiveFullPath.size() - currentIndex - 1;
                if (remaining <= 0) {
                    if (traceRegistry != null) {
                        traceRegistry.markFinished(original.getTaskNo(), traceVersion, currentStation.getStationId(),
                                buildDetails("targetStationId", original.getTargetStaNo(), "routeVersion", original.getRouteVersion()));
                    }
                    markFinished(original.getTaskNo(), original.getRouteVersion(), currentStation.getStationId());
                    break;
                }
 
                StationCommand currentSegmentCommand = localPlan.getSegmentCommands().get(segCursor);
                int currentSegEndIndex = safeIndex(currentSegmentCommand.getSegmentEndIndex());
                int currentSegStartIndex = segCursor == 0
                        ? 0
                        : safeIndex(localPlan.getSegmentCommands().get(segCursor - 1).getSegmentEndIndex());
                int segLen = currentSegEndIndex - currentSegStartIndex + 1;
                int remainingSegment = Math.max(0, currentSegEndIndex - currentIndex);
                int thresholdSegment = (int) Math.ceil(segLen * loadSegmentAdvanceRatio());
                thresholdSegment = Math.max(1, thresholdSegment);
                if (remainingSegment <= thresholdSegment
                        && segCursor < localPlan.getSegmentCommands().size() - 1) {
                    StationCommand nextCommand = localPlan.getSegmentCommands().get(segCursor + 1);
                    if (sendSegmentWithRetry(nextCommand, traceRegistry, traceVersion, currentStation.getStationId())) {
                        segCursor++;
                        if (traceRegistry != null) {
                            traceRegistry.markSegmentIssued(original.getTaskNo(), traceVersion, nextCommand,
                                    "NEXT_SEGMENT_SENT", "输送任务下一段已提前下发",
                                    buildSegmentDetails(nextCommand));
                        }
                    } else {
                        break;
                    }
                }
                Thread.sleep(500L);
                firstRun = false;
            } catch (Exception ignore) {
                break;
            }
        }
    }
 
    private boolean sendSegmentWithRetry(StationCommand command,
                                         StationTaskTraceRegistry traceRegistry,
                                         Integer traceVersion,
                                         Integer currentStationId) {
        while (true) {
            if (!isRouteActive(command == null ? null : command.getTaskNo(), command == null ? null : command.getRouteVersion())) {
                if (traceRegistry != null && command != null) {
                    traceRegistry.markCancelled(command.getTaskNo(), traceVersion, currentStationId,
                            buildDetails("reason", "route_version_replaced", "routeVersion", command.getRouteVersion()));
                }
                markCancelled(command == null ? null : command.getTaskNo(),
                        command == null ? null : command.getRouteVersion(),
                        currentStationId,
                        "route_version_replaced");
                return false;
            }
            if (isTaskMoveReset(command == null ? null : command.getTaskNo())) {
                if (traceRegistry != null && command != null) {
                    traceRegistry.markCancelled(command.getTaskNo(), traceVersion, currentStationId,
                            buildDetails("reason", "redis_cancel_signal", "routeVersion", command.getRouteVersion()));
                }
                markCancelled(command == null ? null : command.getTaskNo(),
                        command == null ? null : command.getRouteVersion(),
                        currentStationId,
                        "redis_cancel_signal");
                return false;
            }
            CommandResponse commandResponse = commandSender.apply(command);
            if (commandResponse == null) {
                sleepQuietly(200L);
                continue;
            }
            if (commandResponse.getResult()) {
                markSegmentIssued(command == null ? null : command.getTaskNo(), command == null ? null : command.getRouteVersion());
                return true;
            }
            sleepQuietly(200L);
        }
    }
 
    private double loadSegmentAdvanceRatio() {
        try {
            ConfigService configService = SpringUtils.getBean(ConfigService.class);
            if (configService == null) {
                return DEFAULT_STATION_COMMAND_SEGMENT_ADVANCE_RATIO;
            }
            Config config = configService.getOne(new QueryWrapper<Config>()
                    .eq("code", CFG_STATION_COMMAND_SEGMENT_ADVANCE_RATIO));
            if (config == null || Cools.isEmpty(config.getValue())) {
                return DEFAULT_STATION_COMMAND_SEGMENT_ADVANCE_RATIO;
            }
            return normalizeSegmentAdvanceRatio(config.getValue());
        } catch (Exception ignore) {
            return DEFAULT_STATION_COMMAND_SEGMENT_ADVANCE_RATIO;
        }
    }
 
    private double normalizeSegmentAdvanceRatio(String valueText) {
        if (valueText == null) {
            return DEFAULT_STATION_COMMAND_SEGMENT_ADVANCE_RATIO;
        }
        String text = valueText.trim();
        if (text.isEmpty()) {
            return DEFAULT_STATION_COMMAND_SEGMENT_ADVANCE_RATIO;
        }
        if (text.endsWith("%")) {
            text = text.substring(0, text.length() - 1).trim();
        }
        try {
            double ratio = Double.parseDouble(text);
            if (ratio > 1d && ratio <= 100d) {
                ratio = ratio / 100d;
            }
            if (ratio < 0d) {
                return 0d;
            }
            if (ratio > 1d) {
                return 1d;
            }
            return ratio;
        } catch (Exception ignore) {
            return DEFAULT_STATION_COMMAND_SEGMENT_ADVANCE_RATIO;
        }
    }
 
    private boolean isTaskMoveReset(Integer taskNo) {
        if (taskNo == null || redisUtil == null) {
            return false;
        }
        Object cancel = redisUtil.get(RedisKeyType.DEVICE_STATION_MOVE_RESET.key + taskNo);
        return cancel != null;
    }
 
    private StationProtocol findCurrentStationByTask(Integer taskNo) {
        try {
            com.zy.asrs.service.DeviceConfigService deviceConfigService = SpringUtils.getBean(com.zy.asrs.service.DeviceConfigService.class);
            if (deviceConfigService == null) {
                return null;
            }
            List<DeviceConfig> devpList = deviceConfigService.list(new QueryWrapper<DeviceConfig>()
                    .eq("device_type", String.valueOf(SlaveType.Devp)));
            for (DeviceConfig dc : devpList) {
                com.zy.core.thread.StationThread thread = (com.zy.core.thread.StationThread) SlaveConnection.get(SlaveType.Devp, dc.getDeviceNo());
                if (thread == null) {
                    continue;
                }
                Map<Integer, StationProtocol> statusMap = thread.getStatusMap();
                if (statusMap == null || statusMap.isEmpty()) {
                    continue;
                }
                for (StationProtocol protocol : statusMap.values()) {
                    if (protocol.getTaskNo() != null && protocol.getTaskNo().equals(taskNo) && protocol.isLoading()) {
                        return protocol;
                    }
                }
            }
        } catch (Exception ignore) {
            return null;
        }
        return null;
    }
 
    private List<StationTaskTraceSegmentVo> buildTraceSegments(List<StationCommand> segmentCommands) {
        List<StationTaskTraceSegmentVo> result = new ArrayList<>();
        if (segmentCommands == null) {
            return result;
        }
        for (StationCommand command : segmentCommands) {
            if (command == null) {
                continue;
            }
            StationTaskTraceSegmentVo item = new StationTaskTraceSegmentVo();
            item.setSegmentNo(command.getSegmentNo());
            item.setSegmentCount(command.getSegmentCount());
            item.setStationId(command.getStationId());
            item.setTargetStationId(command.getTargetStaNo());
            item.setSegmentStartIndex(command.getSegmentStartIndex());
            item.setSegmentEndIndex(command.getSegmentEndIndex());
            item.setSegmentPath(copyIntegerList(command.getNavigatePath()));
            item.setIssued(Boolean.FALSE);
            result.add(item);
        }
        return result;
    }
 
    private void bindCommands(List<StationCommand> segmentCommands, int traceVersion, int pathOffset, Integer routeVersion) {
        if (segmentCommands == null) {
            return;
        }
        for (StationCommand command : segmentCommands) {
            if (command == null) {
                continue;
            }
            command.setTraceVersion(traceVersion);
            command.setRouteVersion(routeVersion);
            if (command.getSegmentStartIndex() != null) {
                command.setSegmentStartIndex(command.getSegmentStartIndex() + pathOffset);
            }
            if (command.getSegmentEndIndex() != null) {
                command.setSegmentEndIndex(command.getSegmentEndIndex() + pathOffset);
            }
        }
    }
 
    private Map<String, Object> buildSegmentDetails(StationCommand command) {
        Map<String, Object> details = new LinkedHashMap<>();
        if (command != null) {
            details.put("segmentNo", command.getSegmentNo());
            details.put("segmentCount", command.getSegmentCount());
            details.put("segmentPath", copyIntegerList(command.getNavigatePath()));
            details.put("segmentStartIndex", command.getSegmentStartIndex());
            details.put("segmentEndIndex", command.getSegmentEndIndex());
            details.put("traceVersion", command.getTraceVersion());
            details.put("routeVersion", command.getRouteVersion());
        }
        return details;
    }
 
    private Map<String, Object> buildDetails(Object... keyValues) {
        Map<String, Object> details = new LinkedHashMap<>();
        if (keyValues == null) {
            return details;
        }
        for (int i = 0; i + 1 < keyValues.length; i += 2) {
            Object key = keyValues[i];
            if (key != null) {
                details.put(String.valueOf(key), keyValues[i + 1]);
            }
        }
        return details;
    }
 
    private List<Integer> copyIntegerList(List<Integer> source) {
        List<Integer> result = new ArrayList<>();
        if (source != null) {
            result.addAll(source);
        }
        return result;
    }
 
    private int safeIndex(Integer value) {
        return value == null ? -1 : value;
    }
 
    private boolean equalsInteger(Integer a, Integer b) {
        return a != null && a.equals(b);
    }
 
    private void sleepQuietly(long millis) {
        try {
            Thread.sleep(millis);
        } catch (Exception ignore) {
        }
    }
 
    private boolean isRouteActive(Integer taskNo, Integer routeVersion) {
        // Legacy direct-enqueue commands (for example FakeProcess/stationInExecute)
        // do not register a move session and therefore have no routeVersion.
        // They should keep the historical behavior and execute normally.
        if (taskNo == null || routeVersion == null) {
            return true;
        }
        StationMoveCoordinator moveCoordinator = SpringUtils.getBean(StationMoveCoordinator.class);
        return moveCoordinator == null || moveCoordinator.isActiveRoute(taskNo, routeVersion);
    }
 
    private void markSegmentIssued(Integer taskNo, Integer routeVersion) {
        StationMoveCoordinator moveCoordinator = SpringUtils.getBean(StationMoveCoordinator.class);
        if (moveCoordinator != null) {
            moveCoordinator.markSegmentIssued(taskNo, routeVersion);
        }
    }
 
    private void updateCurrentStation(Integer taskNo, Integer routeVersion, Integer currentStationId) {
        StationMoveCoordinator moveCoordinator = SpringUtils.getBean(StationMoveCoordinator.class);
        if (moveCoordinator != null) {
            moveCoordinator.updateCurrentStation(taskNo, routeVersion, currentStationId);
        }
    }
 
    private void markCancelled(Integer taskNo, Integer routeVersion, Integer currentStationId, String cancelReason) {
        StationMoveCoordinator moveCoordinator = SpringUtils.getBean(StationMoveCoordinator.class);
        if (moveCoordinator != null) {
            moveCoordinator.markCancelled(taskNo, routeVersion, currentStationId, cancelReason);
        }
    }
 
    private void markBlocked(Integer taskNo, Integer routeVersion, Integer currentStationId) {
        StationMoveCoordinator moveCoordinator = SpringUtils.getBean(StationMoveCoordinator.class);
        if (moveCoordinator != null) {
            moveCoordinator.markBlocked(taskNo, routeVersion, currentStationId);
        }
    }
 
    private void markTimeout(Integer taskNo, Integer routeVersion, Integer currentStationId) {
        StationMoveCoordinator moveCoordinator = SpringUtils.getBean(StationMoveCoordinator.class);
        if (moveCoordinator != null) {
            moveCoordinator.markTimeout(taskNo, routeVersion, currentStationId);
        }
    }
 
    private void markFinished(Integer taskNo, Integer routeVersion, Integer currentStationId) {
        StationMoveCoordinator moveCoordinator = SpringUtils.getBean(StationMoveCoordinator.class);
        if (moveCoordinator != null) {
            moveCoordinator.markFinished(taskNo, routeVersion, currentStationId);
        }
    }
}