自动化立体仓库 - WMS系统
zwl
2 天以前 909cc78ba290cefc3c4623eff234e85ca0140e6d
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
package com.zy.integration.iot.biz.impl;
 
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.core.common.Cools;
import com.core.common.R;
import com.zy.asrs.entity.LocMast;
import com.zy.asrs.entity.WrkDetl;
import com.zy.asrs.entity.WrkMast;
import com.zy.asrs.entity.param.MesToCombParam;
import com.zy.asrs.entity.param.OutTaskParam;
import com.zy.asrs.service.ExternalTaskFacadeService;
import com.zy.asrs.service.LocMastService;
import com.zy.asrs.service.WrkDetlService;
import com.zy.integration.iot.biz.IotInstructionService;
import com.zy.iot.config.IotProperties;
import com.zy.iot.constant.IotConstants;
import com.zy.iot.entity.IotFeedbackMessage;
import com.zy.iot.entity.IotInstructionMessage;
import com.zy.iot.entity.IotPublishRecord;
import com.zy.iot.service.IotPublishRecordService;
import com.zy.iot.util.IotInstructionIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
 
/**
 * IoT 指令核心编排服务。
 * 负责把 XBPS 下发的 MQTT 指令转换成现有 ASRS 入库/出库流程,并在本地记录幂等、乱序和回执状态。
 */
@Slf4j
@Service
public class IotInstructionServiceImpl implements IotInstructionService {
 
    @Autowired
    private IotPublishRecordService iotPublishRecordService;
    @Autowired
    private IotProperties iotProperties;
    @Autowired
    private ExternalTaskFacadeService externalTaskFacadeService;
    @Autowired
    private LocMastService locMastService;
    @Autowired
    private WrkDetlService wrkDetlService;
 
    /**
     * 处理 egress/asrs/stow 指令。
     * 只接单和预登记,不在 MQTT 回调里直接触发真实入库作业。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long handleStowInstruction(IotInstructionMessage message, String topic, String rawPayload) {
        if (message == null || Cools.isEmpty(message.getInstructionId())) {
            log.warn("ignore invalid stow message, payload={}", rawPayload);
            return null;
        }
        IotPublishRecord existing = iotPublishRecordService.findByInstructionId(message.getInstructionId());
        if (existing != null) {
            return existing.getId();
        }
 
        IotPublishRecord record = initInboundRecord(message, topic, rawPayload, IotConstants.MESSAGE_TYPE_STOW);
        iotPublishRecordService.insert(record);
        if (Cools.isEmpty(message.getContainerId())) {
            return updateAsFailure(record, null, "containerId不能为空");
        }
        if (isDelayed(message, IotConstants.MESSAGE_TYPE_STOW)) {
            return updateAsFailure(record, IotConstants.ERROR_CODE_DELAYED, "延迟消息已忽略");
        }
 
        String preferredLocNo = resolvePreferredInboundLoc(message);
        MesToCombParam param = buildInboundParam(message, preferredLocNo);
        R result = externalTaskFacadeService.acceptInboundNotice(param);
        if (result == null || !Objects.equals(result.get("code"), 200)) {
            return updateAsFailure(record, null, resolveResultMessage(result, "接收入库指令失败"));
        }
 
        Date now = new Date();
        record.setOrderNo(param.getOrderId());
        record.setProcessStatus(IotConstants.PROCESS_STATUS_PROCESSED);
        record.setErrorCode(null);
        record.setErrorMessage(null);
        applyFeedback(record, IotConstants.FEEDBACK_SUCCESS, null, null, now);
        iotPublishRecordService.updateById(record);
        return record.getId();
    }
 
    /**
     * 处理 egress/asrs/pick 指令。
     * 远端出库口会先映射成本地站台号,再复用现有出库建单并自动确认放行。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long handlePickInstruction(IotInstructionMessage message, String topic, String rawPayload) {
        if (message == null || Cools.isEmpty(message.getInstructionId())) {
            log.warn("ignore invalid pick message, payload={}", rawPayload);
            return null;
        }
        IotPublishRecord existing = iotPublishRecordService.findByInstructionId(message.getInstructionId());
        if (existing != null) {
            return existing.getId();
        }
 
        IotPublishRecord record = initInboundRecord(message, topic, rawPayload, IotConstants.MESSAGE_TYPE_PICK);
        iotPublishRecordService.insert(record);
        if (Cools.isEmpty(message.getContainerId())) {
            return updateAsFailure(record, null, "containerId不能为空");
        }
        if (isDelayed(message, IotConstants.MESSAGE_TYPE_PICK)) {
            return updateAsFailure(record, IotConstants.ERROR_CODE_DELAYED, "延迟消息已忽略");
        }
 
        String remoteDestination = extractFirstDestination(message.getDestinationLocationIds());
        Integer stationId = Cools.isEmpty(remoteDestination) ? null : iotProperties.getPickStationMappings().get(remoteDestination);
        if (stationId == null) {
            return updateAsFailure(record, IotConstants.ERROR_CODE_STATION_MAPPING, "未找到目标出库口映射");
        }
 
        OutTaskParam param = new OutTaskParam();
        param.setPalletId(message.getContainerId());
        param.setOrderId(resolveReferenceId(message));
        param.setStationId(String.valueOf(stationId));
        param.setSeq(1);
        R result = externalTaskFacadeService.createOutboundTask(param, true);
        if (result == null || !Objects.equals(result.get("code"), 200)) {
            return updateAsFailure(record, null, resolveResultMessage(result, "接收拣货指令失败"));
        }
 
        Date now = new Date();
        record.setOrderNo(param.getOrderId());
        record.setWrkNo(resolveWrkNo(result));
        record.setProcessStatus(IotConstants.PROCESS_STATUS_PROCESSED);
        record.setErrorCode(null);
        record.setErrorMessage(null);
        applyFeedback(record, IotConstants.FEEDBACK_SUCCESS, null, null, now);
        iotPublishRecordService.updateById(record);
        return record.getId();
    }
 
    /**
     * 处理 XBPS 对 ASRS 动作消息的 feedback 回执。
     * 这里只回写 IoT 发布状态,不改库存和工作档。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleFeedbackAck(IotFeedbackMessage feedbackMessage, String topic, String rawPayload) {
        if (feedbackMessage == null || Cools.isEmpty(feedbackMessage.getInstructionId())) {
            return;
        }
        IotPublishRecord record = iotPublishRecordService.findByInstructionId(feedbackMessage.getInstructionId());
        if (record == null || !IotConstants.DIRECTION_OUTBOUND.equals(record.getDirection())) {
            log.warn("ignore iot ack without outbound record, instructionId={}", feedbackMessage.getInstructionId());
            return;
        }
        Date now = new Date();
        record.setAckPayload(rawPayload);
        record.setAckTime(now);
        record.setReceiveTopic(topic);
        record.setPublishStatus(IotConstants.FEEDBACK_SUCCESS.equalsIgnoreCase(feedbackMessage.getStatus())
                ? IotConstants.PUBLISH_STATUS_ACK_SUCCESS
                : IotConstants.PUBLISH_STATUS_ACK_FAILURE);
        record.setErrorCode(feedbackMessage.getErrorCode());
        record.setErrorMessage(truncate(feedbackMessage.getMessage(), 500));
        record.setUpdateTime(now);
        iotPublishRecordService.updateById(record);
    }
 
    /**
     * 在工作档真正完成后落一条待发布记录。
     * 事务内只写库,不直接发 MQTT,避免业务提交和网络发送耦合。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void queueWorkCompletion(WrkMast wrkMast) {
        if (!iotProperties.isEnabled() || wrkMast == null || wrkMast.getWrkNo() == null) {
            return;
        }
        IotPublishRecord existed = iotPublishRecordService.selectOne(new EntityWrapper<IotPublishRecord>()
                .eq("direction", IotConstants.DIRECTION_OUTBOUND)
                .eq("wrk_no", wrkMast.getWrkNo()));
        if (existed != null) {
            return;
        }
        IotPublishRecord record = buildOutboundRecord(wrkMast);
        if (record != null) {
            iotPublishRecordService.insert(record);
        }
    }
 
    private IotPublishRecord initInboundRecord(IotInstructionMessage message, String topic, String rawPayload, String messageType) {
        Date now = new Date();
        IotPublishRecord record = new IotPublishRecord();
        record.setInstructionId(message.getInstructionId());
        record.setDirection(IotConstants.DIRECTION_INBOUND);
        record.setMessageType(messageType);
        record.setReceiveTopic(topic);
        record.setContainerId(message.getContainerId());
        record.setReferenceId(message.getReferenceId());
        record.setSourceLocationId(message.getSourceLocationId());
        record.setDestinationLocationIds(normalizeDestinations(message.getDestinationLocationIds()));
        record.setMessageCreationTime(resolveCreationTime(message.getCreationTime()));
        record.setRawPayload(rawPayload);
        record.setProcessStatus(IotConstants.PROCESS_STATUS_RECEIVED);
        record.setPublishStatus(IotConstants.PUBLISH_STATUS_NOT_REQUIRED);
        record.setCreateTime(now);
        record.setUpdateTime(now);
        return record;
    }
 
    private boolean isDelayed(IotInstructionMessage message, String messageType) {
        Long creationTime = resolveCreationTime(message.getCreationTime());
        IotPublishRecord latest = iotPublishRecordService.findLatestInboundInstruction(message.getContainerId(), messageType);
        return latest != null && latest.getMessageCreationTime() != null && latest.getMessageCreationTime() > creationTime;
    }
 
    /**
     * IoT 文档未提供物料和数量明细,这里沿用现有满托入库通知的兜底约定。
     */
    private MesToCombParam buildInboundParam(IotInstructionMessage message, String preferredLocNo) {
        MesToCombParam param = new MesToCombParam();
        param.setPalletId(message.getContainerId());
        param.setOrderId("");
        param.setBizNo(message.getInstructionId());
        param.setAnfme(1D);
        param.setFull(1);
        param.setLocId(preferredLocNo);
        param.setBoxType1("aws");
        return param;
    }
 
    /**
     * 仅当指定库位当前仍为空位时才强制优先使用,否则回退到原有自动找位。
     */
    private String resolvePreferredInboundLoc(IotInstructionMessage message) {
        String preferredLoc = extractFirstDestination(message.getDestinationLocationIds());
        if (Cools.isEmpty(preferredLoc)) {
            return null;
        }
        LocMast locMast = locMastService.selectById(preferredLoc);
        if (locMast != null && "O".equalsIgnoreCase(locMast.getLocSts())) {
            return locMast.getLocNo();
        }
        return null;
    }
 
    private String resolveReferenceId(IotInstructionMessage message) {
        return Cools.isEmpty(message.getReferenceId()) ? message.getInstructionId() : message.getReferenceId();
    }
 
    private Long updateAsFailure(IotPublishRecord record, String errorCode, String errorMessage) {
        Date now = new Date();
        record.setProcessStatus(IotConstants.PROCESS_STATUS_FAILED);
        record.setOrderNo(Cools.isEmpty(record.getOrderNo()) ? record.getReferenceId() : record.getOrderNo());
        record.setErrorCode(errorCode);
        record.setErrorMessage(truncate(errorMessage, 500));
        applyFeedback(record, IotConstants.FEEDBACK_FAILURE, errorCode, errorMessage, now);
        iotPublishRecordService.updateById(record);
        return record.getId();
    }
 
    private void applyFeedback(IotPublishRecord record, String status, String errorCode, String errorMessage, Date now) {
        IotFeedbackMessage feedbackMessage = new IotFeedbackMessage();
        feedbackMessage.setInstructionId(record.getInstructionId());
        feedbackMessage.setStatus(status);
        feedbackMessage.setErrorCode(errorCode);
        feedbackMessage.setMessage(errorMessage);
        feedbackMessage.setCreationTime(System.currentTimeMillis());
 
        record.setFeedbackStatus(status);
        record.setPublishTopic(iotProperties.getTopics().getIngressFeedback());
        record.setPublishPayload(JSON.toJSONString(feedbackMessage));
        record.setPublishStatus(IotConstants.PUBLISH_STATUS_PENDING);
        record.setUpdateTime(now);
    }
 
    private String resolveResultMessage(R result, String defaultMessage) {
        if (result == null) {
            return defaultMessage;
        }
        Object msg = result.get("msg");
        return msg == null ? defaultMessage : String.valueOf(msg);
    }
 
    private Integer resolveWrkNo(R result) {
        if (result == null) {
            return null;
        }
        Object wrkNo = result.get("wrkNo");
        if (wrkNo instanceof Number) {
            return ((Number) wrkNo).intValue();
        }
        if (wrkNo instanceof String && !Cools.isEmpty(String.valueOf(wrkNo))) {
            return Integer.valueOf(String.valueOf(wrkNo));
        }
        return null;
    }
 
    private IotPublishRecord buildOutboundRecord(WrkMast wrkMast) {
        Integer ioType = wrkMast.getIoType();
        if (ioType == null) {
            return null;
        }
        String containerId = resolveContainerId(wrkMast);
        if (Cools.isEmpty(containerId)) {
            return null;
        }
        if (Arrays.asList(1, 8, 11, 53, 54, 57).contains(ioType)) {
            return buildStowOutboundRecord(wrkMast, containerId);
        }
        if (Arrays.asList(101, 108).contains(ioType)) {
            return buildPickOutboundRecord(wrkMast, containerId);
        }
        return null;
    }
 
    private IotPublishRecord buildStowOutboundRecord(WrkMast wrkMast, String containerId) {
        List<String> destinationLocationIds = wrkMast.getLocNo() == null
                ? Collections.<String>emptyList()
                : Collections.singletonList(wrkMast.getLocNo());
        if (destinationLocationIds.isEmpty()) {
            return null;
        }
        IotInstructionMessage payload = new IotInstructionMessage();
        payload.setInstructionId(IotInstructionIdGenerator.generate(String.valueOf(wrkMast.getWrkNo())));
        payload.setContainerId(containerId);
        if (Objects.equals(wrkMast.getIoType(), 11)) {
            payload.setSourceLocationId(wrkMast.getSourceLocNo());
        }
        payload.setDestinationLocationIds(destinationLocationIds);
        if (!Cools.isEmpty(wrkMast.getUserNo())) {
            payload.setReferenceId(wrkMast.getUserNo());
        }
        payload.setCreationTime(System.currentTimeMillis());
        return initOutboundRecord(wrkMast, IotConstants.MESSAGE_TYPE_STOW, iotProperties.getTopics().getIngressStow(), payload);
    }
 
    private IotPublishRecord buildPickOutboundRecord(WrkMast wrkMast, String containerId) {
        IotInstructionMessage payload = new IotInstructionMessage();
        payload.setInstructionId(IotInstructionIdGenerator.generate(String.valueOf(wrkMast.getWrkNo())));
        payload.setContainerId(containerId);
        payload.setSourceLocationId(wrkMast.getSourceLocNo());
        payload.setDestinationLocationIds(Collections.singletonList(resolveRemoteStationId(wrkMast.getStaNo())));
        if (!Cools.isEmpty(wrkMast.getUserNo())) {
            payload.setReferenceId(wrkMast.getUserNo());
        }
        payload.setCreationTime(System.currentTimeMillis());
        return initOutboundRecord(wrkMast, IotConstants.MESSAGE_TYPE_PICK, iotProperties.getTopics().getIngressPick(), payload);
    }
 
    private IotPublishRecord initOutboundRecord(WrkMast wrkMast, String messageType, String publishTopic, IotInstructionMessage payload) {
        Date now = new Date();
        IotPublishRecord record = new IotPublishRecord();
        record.setInstructionId(payload.getInstructionId());
        record.setDirection(IotConstants.DIRECTION_OUTBOUND);
        record.setMessageType(messageType);
        record.setPublishTopic(publishTopic);
        record.setContainerId(payload.getContainerId());
        record.setReferenceId(payload.getReferenceId());
        record.setSourceLocationId(payload.getSourceLocationId());
        record.setDestinationLocationIds(normalizeDestinations(payload.getDestinationLocationIds()));
        record.setMessageCreationTime(payload.getCreationTime());
        record.setPublishPayload(JSON.toJSONString(payload));
        record.setRawPayload(record.getPublishPayload());
        record.setProcessStatus(IotConstants.PROCESS_STATUS_PENDING);
        record.setPublishStatus(IotConstants.PUBLISH_STATUS_PENDING);
        record.setWrkNo(wrkMast.getWrkNo());
        record.setOrderNo(wrkMast.getUserNo());
        record.setCreateTime(now);
        record.setUpdateTime(now);
        return record;
    }
 
    private String resolveContainerId(WrkMast wrkMast) {
        if (!Cools.isEmpty(wrkMast.getBarcode())) {
            return wrkMast.getBarcode();
        }
        List<WrkDetl> wrkDetls = wrkDetlService.selectList(new EntityWrapper<WrkDetl>().eq("wrk_no", wrkMast.getWrkNo()));
        if (Cools.isEmpty(wrkDetls)) {
            return null;
        }
        for (WrkDetl wrkDetl : wrkDetls) {
            if (!Cools.isEmpty(wrkDetl.getZpallet())) {
                return wrkDetl.getZpallet();
            }
        }
        return null;
    }
 
    private String resolveRemoteStationId(Integer staNo) {
        if (staNo == null) {
            return null;
        }
        for (Map.Entry<String, Integer> entry : iotProperties.getPickStationMappings().entrySet()) {
            if (Objects.equals(entry.getValue(), staNo)) {
                return entry.getKey();
            }
        }
        return String.valueOf(staNo);
    }
 
    private String extractFirstDestination(List<String> destinationLocationIds) {
        if (Cools.isEmpty(destinationLocationIds)) {
            return null;
        }
        for (String destinationLocationId : destinationLocationIds) {
            if (!Cools.isEmpty(destinationLocationId)) {
                return destinationLocationId;
            }
        }
        return null;
    }
 
    private Long resolveCreationTime(Long creationTime) {
        return creationTime == null ? System.currentTimeMillis() : creationTime;
    }
 
    private String normalizeDestinations(List<String> destinationLocationIds) {
        if (Cools.isEmpty(destinationLocationIds)) {
            return null;
        }
        return JSON.toJSONString(new ArrayList<String>(destinationLocationIds));
    }
 
    private String truncate(String message, int maxLength) {
        if (message == null || message.length() <= maxLength) {
            return message;
        }
        return message.substring(0, maxLength);
    }
}