自动化立体仓库 - 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
package com.zy.integration.iot.publish.impl;
 
import com.core.common.Cools;
import com.zy.integration.iot.client.IotMqttClient;
import com.zy.integration.iot.publish.IotPublishService;
import com.zy.iot.constant.IotConstants;
import com.zy.iot.entity.IotPublishRecord;
import com.zy.iot.service.IotPublishRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.Date;
 
/**
 * IoT 统一发布器。
 * 这里只处理 MQTT 传输结果,业务成功与否由指令处理阶段决定。
 */
@Slf4j
@Service
public class IotPublishServiceImpl implements IotPublishService {
 
    @Autowired
    private IotPublishRecordService iotPublishRecordService;
    @Autowired
    private IotMqttClient iotMqttClient;
 
    /**
     * 立即发布指定记录;若网络发送失败,仅更新状态,后续由调度器重试。
     */
    @Override
    public void publishRecordNow(Long recordId) {
        if (recordId == null) {
            return;
        }
        IotPublishRecord record = iotPublishRecordService.selectById(recordId);
        if (record == null || Cools.isEmpty(record.getPublishTopic()) || Cools.isEmpty(record.getPublishPayload())) {
            return;
        }
        Date now = new Date();
        try {
            iotMqttClient.publish(record.getPublishTopic(), record.getPublishPayload());
            record.setPublishStatus(IotConstants.PUBLISH_STATUS_SUCCESS);
            record.setUpdateTime(now);
            iotPublishRecordService.updateById(record);
        } catch (Exception e) {
            record.setPublishStatus(IotConstants.PUBLISH_STATUS_FAILURE);
            record.setErrorMessage(truncate(e.getMessage(), 500));
            record.setUpdateTime(now);
            iotPublishRecordService.updateById(record);
            log.error("publish iot message failed, recordId={}", recordId, e);
        }
    }
 
    private String truncate(String message, int maxLength) {
        if (message == null || message.length() <= maxLength) {
            return message;
        }
        return message.substring(0, maxLength);
    }
}