|
|
|
@ -2,27 +2,40 @@ package com.shxy.xymanager_framework.mqtt;
|
|
|
|
|
|
|
|
|
|
import com.shxy.xymanager_common.model.mqtt.MessageSend;
|
|
|
|
|
import com.shxy.xymanager_common.util.JSONUtil;
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
|
import org.eclipse.paho.client.mqttv3.MqttClient;
|
|
|
|
|
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
|
|
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
|
|
|
import org.springframework.scheduling.annotation.Async;
|
|
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
|
|
|
|
import javax.annotation.Resource;
|
|
|
|
|
|
|
|
|
|
@Service
|
|
|
|
|
@Slf4j
|
|
|
|
|
public class MqttPublisherService {
|
|
|
|
|
|
|
|
|
|
@Value("${mqtt.cmdtopic}")
|
|
|
|
|
private String cmdtopic;
|
|
|
|
|
|
|
|
|
|
int mid = 0;
|
|
|
|
|
|
|
|
|
|
@Resource
|
|
|
|
|
private MqttClient mqttClient;
|
|
|
|
|
|
|
|
|
|
private synchronized int getNextMid() {
|
|
|
|
|
mid++;
|
|
|
|
|
return mid;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Async
|
|
|
|
|
public void publish(MessageSend msg) throws Exception {
|
|
|
|
|
msg.setMid(this.getNextMid());
|
|
|
|
|
String json = JSONUtil.object2Json(msg);
|
|
|
|
|
MqttMessage message = new MqttMessage(json.getBytes());
|
|
|
|
|
message.setQos(1);
|
|
|
|
|
message.setRetained(true);
|
|
|
|
|
log.info("mqtt发送消息:" + json);
|
|
|
|
|
mqttClient.publish(cmdtopic, message);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|