Junjie
2026-04-19 d9b0b37cb2ff5b0066c5a6550da34bb78adddc97
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
package com.zy.core.network.fake;
 
import com.alibaba.fastjson.JSON;
import com.zy.asrs.entity.DeviceConfig;
import com.zy.core.News;
import com.zy.core.model.CommandResponse;
import com.zy.core.model.protocol.StationTaskBufferItem;
import com.zy.core.network.entity.ZyStationStatusEntity;
import com.zy.core.thread.support.StationTaskLocationRegistry;
import com.core.common.SpringUtils;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReentrantLock;
 
public class FakeStationStateManager {
 
    private final StationTaskLocationRegistry stationTaskLocationRegistry = SpringUtils.getBean(StationTaskLocationRegistry.class);
 
    private interface StationMutation {
        void apply(ZyStationStatusEntity status);
    }
 
    private interface StationRead<T> {
        T apply(ZyStationStatusEntity status);
    }
 
    private final Map<Integer, List<ZyStationStatusEntity>> deviceStatusMap = new ConcurrentHashMap<Integer, List<ZyStationStatusEntity>>();
    private final Map<Integer, DeviceConfig> deviceConfigMap = new ConcurrentHashMap<Integer, DeviceConfig>();
    private final Map<Integer, ReentrantLock> stationLocks = new ConcurrentHashMap<Integer, ReentrantLock>();
 
    private interface StationLockedMutation {
        void apply(ZyStationStatusEntity status);
    }
 
    private interface StationLockedRead<T> {
        T apply(ZyStationStatusEntity status);
    }
 
    private ReentrantLock getStationLock(Integer stationId) {
        return stationLocks.computeIfAbsent(stationId, key -> new ReentrantLock());
    }
 
    public void lockStations(Integer... stationIds) {
        if (stationIds == null || stationIds.length == 0) {
            return;
        }
        Integer[] sorted = java.util.Arrays.copyOf(stationIds, stationIds.length);
        java.util.Arrays.sort(sorted);
        for (Integer stationId : sorted) {
            if (stationId != null) {
                getStationLock(stationId).lock();
            }
        }
    }
 
    public void unlockStations(Integer... stationIds) {
        if (stationIds == null || stationIds.length == 0) {
            return;
        }
        Integer[] sorted = java.util.Arrays.copyOf(stationIds, stationIds.length);
        java.util.Arrays.sort(sorted);
        for (int i = sorted.length - 1; i >= 0; i--) {
            Integer stationId = sorted[i];
            if (stationId != null) {
                getStationLock(stationId).unlock();
            }
        }
    }
 
    private boolean mutateLockedStation(Integer deviceNo, Integer stationId, StationLockedMutation mutation) {
        if (stationId == null || mutation == null) {
            return false;
        }
        lockStations(stationId);
        try {
            ZyStationStatusEntity status = findStationStatus(deviceNo, stationId);
            if (status == null) {
                return false;
            }
            mutation.apply(status);
            return true;
        } finally {
            unlockStations(stationId);
        }
    }
 
    private <T> T readLockedStation(Integer deviceNo, Integer stationId, StationLockedRead<T> read) {
        if (stationId == null || read == null) {
            return null;
        }
        lockStations(stationId);
        try {
            ZyStationStatusEntity status = findStationStatus(deviceNo, stationId);
            if (status == null) {
                return null;
            }
            return read.apply(status);
        } finally {
            unlockStations(stationId);
        }
    }
 
    private boolean updateStationDataWithinLock(Integer stationId, Integer deviceNo, Integer taskNo, Integer targetStaNo,
            Boolean isLoading, String barcode, Boolean runBlock) {
        ZyStationStatusEntity currentStatus = findStationStatus(deviceNo, stationId);
        if (currentStatus == null) {
            return false;
        }
        if (taskNo != null) {
            currentStatus.setTaskNo(taskNo);
        }
        if (targetStaNo != null) {
            currentStatus.setTargetStaNo(targetStaNo);
        }
        if (isLoading != null) {
            currentStatus.setLoading(isLoading);
        }
        if (barcode != null) {
            currentStatus.setBarcode(barcode);
        }
        if (runBlock != null) {
            currentStatus.setRunBlock(runBlock);
        }
        syncTaskLocationInternal(deviceNo, currentStatus);
        return true;
    }
 
 
    public void registerDevice(DeviceConfig deviceConfig) {
        if (deviceConfigMap.containsKey(deviceConfig.getDeviceNo())) {
            return;
        }
        deviceConfigMap.put(deviceConfig.getDeviceNo(), deviceConfig);
        deviceStatusMap.put(deviceConfig.getDeviceNo(), new CopyOnWriteArrayList<ZyStationStatusEntity>());
    }
 
    public Map<Integer, List<ZyStationStatusEntity>> getDeviceStatusMap() {
        return deviceStatusMap;
    }
 
    public Map<Integer, DeviceConfig> getDeviceConfigMap() {
        return deviceConfigMap;
    }
 
    public List<ZyStationStatusEntity> getStatus(Integer deviceNo) {
        List<ZyStationStatusEntity> statusList = deviceStatusMap.get(deviceNo);
        if (statusList == null) {
            return new ArrayList<ZyStationStatusEntity>();
        }
 
        DeviceConfig deviceConfig = deviceConfigMap.get(deviceNo);
        if (statusList.isEmpty() && deviceConfig != null) {
            List<ZyStationStatusEntity> init = JSON.parseArray(deviceConfig.getFakeInitStatus(),
                    ZyStationStatusEntity.class);
            if (init != null) {
                statusList.addAll(init);
                for (ZyStationStatusEntity status : statusList) {
                    status.setAutoing(true);
                    status.setLoading(false);
                    status.setInEnable(true);
                    status.setOutEnable(true);
                    status.setIoMode(2);
                    status.setEmptyMk(false);
                    status.setFullPlt(false);
                    status.setRunBlock(false);
                    status.setPalletHeight(0);
                    status.setError(0);
                    status.setBarcode("");
                }
            }
        }
 
        return statusList;
    }
 
    public ZyStationStatusEntity findStationStatus(Integer deviceNo, Integer stationId) {
        if (deviceNo == null || stationId == null) {
            return null;
        }
        List<ZyStationStatusEntity> statusList = deviceStatusMap.get(deviceNo);
        if (statusList == null) {
            return null;
        }
        return statusList.stream()
                .filter(item -> item.getStationId().equals(stationId))
                .findFirst().orElse(null);
    }
 
    public Integer getDeviceNoByStationId(Integer stationId) {
        for (Map.Entry<Integer, List<ZyStationStatusEntity>> entry : deviceStatusMap.entrySet()) {
            List<ZyStationStatusEntity> list = entry.getValue();
            if (list == null) {
                continue;
            }
            for (ZyStationStatusEntity entity : list) {
                if (entity.getStationId() != null && entity.getStationId().equals(stationId)) {
                    return entry.getKey();
                }
            }
        }
        return null;
    }
 
    public Integer findCurrentStationIdByTask(Integer taskNo) {
        for (List<ZyStationStatusEntity> list : deviceStatusMap.values()) {
            if (list == null) {
                continue;
            }
            for (ZyStationStatusEntity entity : list) {
                Integer stationId = entity == null ? null : entity.getStationId();
                Integer matchedStationId = stationId == null ? null : readStation(getDeviceNoByStationId(stationId), stationId,
                        new StationRead<Integer>() {
                            @Override
                            public Integer apply(ZyStationStatusEntity status) {
                                if (status.getTaskNo() != null && status.getTaskNo().equals(taskNo) && status.isLoading()) {
                                    return status.getStationId();
                                }
                                return null;
                            }
                        });
                if (matchedStationId != null) {
                    return matchedStationId;
                }
            }
        }
        return null;
    }
 
    public String getThreadImpl(Integer deviceNo) {
        DeviceConfig deviceConfig = deviceConfigMap.get(deviceNo);
        return deviceConfig == null ? "" : deviceConfig.getThreadImpl();
    }
 
    public boolean isStationLoadingTask(Integer deviceNo, Integer stationId, Integer taskNo) {
        Boolean result = readStation(deviceNo, stationId, new StationRead<Boolean>() {
            @Override
            public Boolean apply(ZyStationStatusEntity status) {
                return status.getTaskNo() != null && status.getTaskNo().equals(taskNo) && status.isLoading();
            }
        });
        return Boolean.TRUE.equals(result);
    }
 
    public boolean isStationClearedForTask(Integer deviceNo, Integer stationId, Integer taskNo) {
        Boolean result = readStation(deviceNo, stationId, new StationRead<Boolean>() {
            @Override
            public Boolean apply(ZyStationStatusEntity status) {
                boolean emptyStation = !status.isLoading()
                        && (status.getTaskNo() == null || status.getTaskNo() <= 0);
                return emptyStation;
            }
        });
        return result == null || result;
    }
 
    public boolean isFinalStationOwnerConflict(Integer deviceNo, Integer stationId, Integer taskNo) {
        Boolean result = readStation(deviceNo, stationId, new StationRead<Boolean>() {
            @Override
            public Boolean apply(ZyStationStatusEntity status) {
                return status.isLoading()
                        && taskNo != null
                        && status.getTaskNo() != null
                        && status.getTaskNo() > 0
                        && !taskNo.equals(status.getTaskNo());
            }
        });
        return Boolean.TRUE.equals(result);
    }
 
    public boolean isOccupiedByOtherLoadingTask(Integer deviceNo, Integer stationId, Integer taskNo) {
        Boolean result = readStation(deviceNo, stationId, new StationRead<Boolean>() {
            @Override
            public Boolean apply(ZyStationStatusEntity status) {
                return status.isLoading()
                        && status.getTaskNo() != null
                        && status.getTaskNo() > 0
                        && (taskNo == null || !taskNo.equals(status.getTaskNo()));
            }
        });
        return Boolean.TRUE.equals(result);
    }
 
    public ZyStationStatusEntity snapshotStation(Integer deviceNo, Integer stationId) {
        return readStation(deviceNo, stationId, new StationRead<ZyStationStatusEntity>() {
            @Override
            public ZyStationStatusEntity apply(ZyStationStatusEntity status) {
                return JSON.parseObject(JSON.toJSONString(status), ZyStationStatusEntity.class);
            }
        });
    }
 
    private boolean mutateStation(Integer deviceNo, Integer stationId, StationMutation mutation) {
        if (mutation == null) {
            return false;
        }
        return mutateLockedStation(deviceNo, stationId, new StationLockedMutation() {
            @Override
            public void apply(ZyStationStatusEntity status) {
                mutation.apply(status);
            }
        });
    }
 
    private <T> T readStation(Integer deviceNo, Integer stationId, StationRead<T> read) {
        if (read == null) {
            return null;
        }
        return readLockedStation(deviceNo, stationId, new StationLockedRead<T>() {
            @Override
            public T apply(ZyStationStatusEntity status) {
                return read.apply(status);
            }
        });
    }
 
    public boolean updateStationDataWithHeldLock(Integer stationId, Integer deviceNo, Integer taskNo, Integer targetStaNo,
            Boolean isLoading, String barcode, Boolean runBlock) {
        return updateStationDataWithinLock(stationId, deviceNo, taskNo, targetStaNo, isLoading, barcode, runBlock);
    }
 
    public boolean updateStationDataInternal(Integer stationId, Integer deviceNo, Integer taskNo, Integer targetStaNo,
            Boolean isLoading, String barcode, Boolean runBlock) {
        return mutateLockedStation(deviceNo, stationId, new StationLockedMutation() {
            @Override
            public void apply(ZyStationStatusEntity currentStatus) {
                updateStationDataWithinLock(stationId, deviceNo, taskNo, targetStaNo, isLoading, barcode, runBlock);
            }
        });
    }
 
    public void syncTaskLocation(Integer deviceNo, Integer stationId) {
        if (deviceNo == null || stationId == null) {
            return;
        }
        readStation(deviceNo, stationId, new StationRead<Void>() {
            @Override
            public Void apply(ZyStationStatusEntity status) {
                syncTaskLocationInternal(deviceNo, status);
                return null;
            }
        });
    }
 
    public void removeTaskLocation(Integer taskNo, Integer deviceNo, Integer stationId) {
        if (stationTaskLocationRegistry == null || taskNo == null || taskNo <= 0) {
            return;
        }
        stationTaskLocationRegistry.remove(taskNo, deviceNo, stationId);
    }
 
    private void syncTaskLocationInternal(Integer deviceNo, ZyStationStatusEntity status) {
        if (stationTaskLocationRegistry == null || deviceNo == null || status == null) {
            return;
        }
        Integer taskNo = status.getTaskNo();
        if (taskNo != null && taskNo > 0 && status.isLoading() && status.getStationId() != null) {
            stationTaskLocationRegistry.update(taskNo, deviceNo, status.getStationId(), true,
                    status.isRunBlock(), System.currentTimeMillis());
        }
    }
 
    public void clearTaskLocationIfMatches(Integer taskNo, Integer deviceNo, Integer stationId) {
        if (taskNo == null || taskNo <= 0 || deviceNo == null || stationId == null) {
            return;
        }
        readStation(deviceNo, stationId, new StationRead<Void>() {
            @Override
            public Void apply(ZyStationStatusEntity status) {
                if (status.getTaskNo() == null || !taskNo.equals(status.getTaskNo()) || !status.isLoading()) {
                    removeTaskLocation(taskNo, deviceNo, stationId);
                }
                return null;
            }
        });
    }
 
    public void publishTaskLocation(Integer taskNo, Integer deviceNo, Integer stationId, boolean loading, boolean runBlock) {
        if (stationTaskLocationRegistry == null || taskNo == null || taskNo <= 0 || deviceNo == null || stationId == null || !loading) {
            return;
        }
        stationTaskLocationRegistry.update(taskNo, deviceNo, stationId, true, runBlock, System.currentTimeMillis());
    }
 
    public void generateStationData(Integer deviceNo, Integer taskNo, Integer stationId, Integer targetStationId) {
        mutateStation(deviceNo, stationId, new StationMutation() {
            @Override
            public void apply(ZyStationStatusEntity status) {
                News.info("仿真站点生成任务数据,设备号={},站点号={},原taskNo={},新taskNo={},原targetStaNo={},新targetStaNo={},原loading={},barcode={}",
                        deviceNo, stationId, status.getTaskNo(), taskNo, status.getTargetStaNo(), targetStationId,
                        status.isLoading(), status.getBarcode());
                status.setTaskNo(taskNo);
                status.setTargetStaNo(targetStationId);
                status.setLoading(false);
            }
        });
    }
 
    public void generateFakeOutStationData(Integer deviceNo, Integer stationId) {
        mutateStation(deviceNo, stationId, new StationMutation() {
            @Override
            public void apply(ZyStationStatusEntity status) {
                News.info("仿真出库站点数据生成,设备号={},站点号={},原taskNo={},原targetStaNo={},原loading={},原barcode={},动作=generateFakeOutStationData",
                        deviceNo, stationId, status.getTaskNo(), status.getTargetStaNo(), status.isLoading(), status.getBarcode());
                status.setLoading(true);
                News.info("仿真出库站点数据生成完成,设备号={},站点号={},新taskNo={},新targetStaNo={},新loading={},新barcode={}",
                        deviceNo, stationId, status.getTaskNo(), status.getTargetStaNo(), status.isLoading(), status.getBarcode());
            }
        });
    }
 
    public void resetStation(Integer deviceNo, Integer stationId) {
        if (findStationStatus(deviceNo, stationId) == null) {
            return;
        }
        clearStationForDispatch(deviceNo, stationId, "resetStation");
    }
 
    public void clearStationForDispatch(Integer deviceNo, Integer stationId, String reason) {
        mutateStation(deviceNo, stationId, new StationMutation() {
            @Override
            public void apply(ZyStationStatusEntity status) {
                News.info("仿真站点状态清除,设备号={},站点号={},原taskNo={},原targetStaNo={},原loading={},原barcode={},动作={}",
                        deviceNo, stationId, status.getTaskNo(), status.getTargetStaNo(), status.isLoading(), status.getBarcode(), reason);
                status.setTaskNo(0);
                status.setTargetStaNo(0);
                status.setLoading(false);
                status.setBarcode("");
                status.setRunBlock(false);
            }
        });
    }
 
    public void handoffBarcodeStation(Integer deviceNo, Integer taskNo, Integer stationId, Integer targetStationId) {
        mutateLockedStation(deviceNo, stationId, new StationLockedMutation() {
            @Override
            public void apply(ZyStationStatusEntity status) {
                News.info("仿真站点生成任务数据,设备号={},站点号={},原taskNo={},新taskNo={},原targetStaNo={},新targetStaNo={},原loading={},barcode={}",
                        deviceNo, stationId, status.getTaskNo(), taskNo, status.getTargetStaNo(), targetStationId,
                        status.isLoading(), status.getBarcode());
                status.setTaskNo(taskNo);
                status.setTargetStaNo(targetStationId);
                status.setLoading(false);
                News.info("仿真站点状态清除,设备号={},站点号={},原taskNo={},原targetStaNo={},原loading={},原barcode={},动作={}",
                        deviceNo, stationId, status.getTaskNo(), status.getTargetStaNo(), status.isLoading(), status.getBarcode(), "barcodeTaskHandoff");
                status.setTaskNo(0);
                status.setTargetStaNo(0);
                status.setLoading(false);
                status.setBarcode("");
                status.setRunBlock(false);
            }
        });
    }
 
    public void updateStationBarcode(Integer deviceNo, Integer stationId, String barcode) {
        mutateStation(deviceNo, stationId, new StationMutation() {
            @Override
            public void apply(ZyStationStatusEntity status) {
                status.setBarcode(barcode);
            }
        });
    }
 
    public boolean generateStationBarcode(Integer lockTaskNo, Integer currentStationId, Integer currentStationDeviceNo) {
        ZyStationStatusEntity currentStatus = findStationStatus(currentStationDeviceNo, currentStationId);
        if (currentStatus == null) {
            return false;
        }
 
        Random random = new Random();
        String barcodeTime = String.valueOf(System.currentTimeMillis());
        String barcode = String.valueOf(random.nextInt(10)) + String.valueOf(random.nextInt(10))
                + barcodeTime.substring(7);
        return updateStationDataInternal(currentStationId, currentStationDeviceNo, null, null, null, barcode, null);
    }
 
    public CommandResponse clearTaskBufferSlot(Integer deviceNo, Integer stationId, Integer slotIdx) {
        if (deviceNo == null || stationId == null || slotIdx == null || slotIdx <= 0) {
            return new CommandResponse(false, "清理缓存区槽位参数无效");
        }
        List<ZyStationStatusEntity> statusList = deviceStatusMap.get(deviceNo);
        if (statusList == null) {
            return new CommandResponse(false, "未找到设备状态");
        }
        for (ZyStationStatusEntity status : statusList) {
            if (status == null || !stationId.equals(status.getStationId())) {
                continue;
            }
            List<StationTaskBufferItem> taskBufferItems = status.getTaskBufferItems();
            if (taskBufferItems == null || taskBufferItems.isEmpty()) {
                return new CommandResponse(true, "缓存区槽位已为空");
            }
            for (StationTaskBufferItem item : taskBufferItems) {
                if (item != null && slotIdx.equals(item.getSlotIdx())) {
                    item.setTaskNo(0);
                    item.setTargetStaNo(0);
                    return new CommandResponse(true, "缓存区槽位清理成功");
                }
            }
            return new CommandResponse(false, "未找到缓存区槽位");
        }
        return new CommandResponse(false, "未找到站点状态");
    }
}