aix
2024-08-14 5d06d78cbf238c383a229f61bf16d3c59051ee9e
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
package com.dji.sample.component.mqtt.service.impl;
 
import com.dji.sample.amap.model.ReceiverData;
import com.dji.sample.component.mqtt.model.*;
import com.dji.sample.component.mqtt.service.IMessageSenderService;
import com.dji.sample.component.mqtt.service.IMqttMessageGateway;
import com.dji.sample.component.rabbitmq.config.MqttMsgProxyProducer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
 
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * @author sean.zhou
 * @version 0.1
 * @date 2021/11/16
 */
@Service
@Slf4j
public class MessageSenderServiceImpl implements IMessageSenderService {
 
    @Autowired
    private IMqttMessageGateway messageGateway;
 
    @Autowired
    private ObjectMapper mapper;
 
    @Value("${spring.rabbitmq.is-open}")
    private Boolean sendRabbitMQ;
 
    @Autowired
    private MqttMsgProxyProducer mqttMsgProxyProducer;
 
    public void publish(String topic, CommonTopicResponse response) {
        this.publish(topic, 1, response);
    }
 
    public void sendRabbitMQ(String topic, Object data) {
        try {
            if (sendRabbitMQ) {
                sendRabbitMQ(topic.replace("/", ".") + ".response", mapper.writeValueAsBytes(data));
            }
        } catch (Exception e) {
            log.error("消息发送失败2:", e);
        }
    }
 
    private void sendRabbitMQ(String topic, byte[] bytes) {
        //发送操作消息至mqtt同时发送到rabbitMQ
        try {
            if (sendRabbitMQ) {
                mqttMsgProxyProducer.publish(topic, bytes);
            }
        } catch (Exception e) {
            log.error("消息发送失败:", e);
        }
    }
 
    public void publish(String topic, int qos, CommonTopicResponse response) {
        try {
            log.info("send topic: {}, payload: {}", topic, response.toString());
            byte[] bytes = mapper.writeValueAsBytes(response);
            sendRabbitMQ(topic, bytes);
            messageGateway.publish(topic, bytes, qos);
        } catch (JsonProcessingException e) {
            log.info("Failed to publish the message. {}", response.toString());
            e.printStackTrace();
        }
    }
 
    public <T> T publishWithReply(Class<T> clazz, String topic, CommonTopicResponse response) {
        return this.publishWithReply(clazz, topic, response, 2);
    }
 
    public <T> T publishWithReply(Class<T> clazz, String topic, CommonTopicResponse response, int retryTime) {
        AtomicInteger time = new AtomicInteger(0);
        ReceiverData receiverData = new ReceiverData();
        receiverData.setTid(response.getTid());
        receiverData.setBid(response.getBid());
        // Retry three times
        while (time.getAndIncrement() <= retryTime) {
            this.publish(topic, response);
 
            Chan<CommonTopicReceiver<T>> chan = Chan.getInstance();
            // If the message is not received in 0.5 seconds then resend it again.
            CommonTopicReceiver<T> receiver = chan.get(response.getTid());
 
            // Need to match tid and bid.
            if (Objects.nonNull(receiver) && receiver.getTid().equals(response.getTid()) &&
                    receiver.getBid().equals(response.getBid())) {
                receiverData.setReceiver(receiver.getData());
                if (clazz.isAssignableFrom(receiver.getData().getClass())) {
//                    sendRabbitMQ(topic, receiverData); 设备会单独发一条操作响应消息
                    return receiver.getData();
                }
                receiverData.setError("类型转换异常:" + clazz.getTypeName());
                sendRabbitMQ(topic, receiverData);
                throw new TypeMismatchException(receiver.getData(), clazz);
            }
            // It must be guaranteed that the tid and bid of each message are different.
            response.setBid(UUID.randomUUID().toString());
            response.setTid(UUID.randomUUID().toString());
        }
        receiverData.setError("没有收到消息回复");
        sendRabbitMQ(topic, receiverData);
        throw new RuntimeException("没有收到消息回复。");
    }
 
    @Override
    public <T> ServiceReply<T> publishServicesTopic(TypeReference<T> clazz, String sn, String method, Object data, String bid) {
        String topic = TopicConst.THING_MODEL_PRE + TopicConst.PRODUCT + sn + TopicConst.SERVICES_SUF;
        ServiceReply reply = this.publishWithReply(ServiceReply.class, topic,
                CommonTopicResponse.builder()
                        .tid(UUID.randomUUID().toString())
                        .bid(StringUtils.hasText(bid) ? bid : UUID.randomUUID().toString())
                        .timestamp(System.currentTimeMillis())
                        .method(method)
                        .data(Objects.requireNonNullElse(data, ""))
                        .build());
        if (Objects.isNull(clazz)) {
            return reply;
        }
        // put together in "output"
        if (Objects.nonNull(reply.getInfo())) {
            reply.setOutput(mapper.convertValue(reply.getInfo(), clazz));
        }
        if (Objects.nonNull(reply.getOutput())) {
            reply.setOutput(mapper.convertValue(reply.getOutput(), clazz));
        }
        return reply;
    }
 
    @Override
    public <T> ServiceReply<T> publishServicesTopic(TypeReference<T> clazz, String sn, String method, Object data, String bid, Long timestamp) {
        String topic = TopicConst.THING_MODEL_PRE + TopicConst.PRODUCT + sn + TopicConst.SERVICES_SUF;
        ServiceReply reply = this.publishWithReply(ServiceReply.class, topic,
                CommonTopicResponse.builder()
                        .tid(UUID.randomUUID().toString())
                        .bid(StringUtils.hasText(bid) ? bid : UUID.randomUUID().toString())
                        .timestamp(timestamp)
                        .method(method)
                        .data(Objects.requireNonNullElse(data, ""))
                        .build());
        if (Objects.isNull(clazz)) {
            return reply;
        }
        // put together in "output"
        if (Objects.nonNull(reply.getInfo())) {
            reply.setOutput(mapper.convertValue(reply.getInfo(), clazz));
        }
        if (Objects.nonNull(reply.getOutput())) {
            reply.setOutput(mapper.convertValue(reply.getOutput(), clazz));
        }
        return reply;
    }
 
    @Override
    public ServiceReply publishServicesTopic(String sn, String method, Object data, String bid, Long timestamp) {
        return this.publishServicesTopic(null, sn, method, data, bid, timestamp);
    }
 
    @Override
    public ServiceReply publishServicesTopic(String sn, String method, Object data, String bid) {
        return this.publishServicesTopic(null, sn, method, data, bid);
    }
 
    @Override
    public <T> ServiceReply<T> publishServicesTopic(TypeReference<T> clazz, String sn, String method, Object data) {
        return this.publishServicesTopic(clazz, sn, method, data, null);
    }
 
    @Override
    public ServiceReply publishServicesTopic(String sn, String method, Object data) {
        return this.publishServicesTopic(null, sn, method, data, null);
    }
 
    @Override
    public <T> ServiceReply<T> publishRequestsTopic(TypeReference<T> clazz, String sn, String method, Object data, String bid) {
        String topic = TopicConst.THING_MODEL_PRE + TopicConst.PRODUCT + sn + TopicConst.REQUESTS_SUF;
        ServiceReply reply = this.publishWithReply(ServiceReply.class, topic,
                CommonTopicResponse.builder()
                        .tid(UUID.randomUUID().toString())
                        .bid(StringUtils.hasText(bid) ? bid : UUID.randomUUID().toString())
                        .timestamp(System.currentTimeMillis())
                        .gateway(sn)
                        .method(method)
                        .data(Objects.requireNonNullElse(data, ""))
                        .build());
        if (Objects.isNull(clazz)) {
            return reply;
        }
        // put together in "output"
        if (Objects.nonNull(reply.getInfo())) {
            reply.setOutput(mapper.convertValue(reply.getInfo(), clazz));
        }
        if (Objects.nonNull(reply.getOutput())) {
            reply.setOutput(mapper.convertValue(reply.getOutput(), clazz));
        }
        return reply;
    }
 
    @Override
    public ServiceReply publishRequestsTopic(String sn, String method, Object data, String bid) {
        return this.publishRequestsTopic(null, sn, method, data, bid);
    }
 
    @Override
    public ServiceReply publishRequestsTopic(String sn, String method, Object data) {
        return this.publishRequestsTopic(null, sn, method, data, null);
    }
 
}