12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- package com.ruoyi.tianao.init;
- import com.ruoyi.tianao.config.MQTTConfig;
- import lombok.extern.slf4j.Slf4j;
- import org.eclipse.paho.client.mqttv3.MqttClient;
- import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
- import org.eclipse.paho.client.mqttv3.MqttException;
- import org.eclipse.paho.client.mqttv3.MqttMessage;
- import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
- import org.springframework.boot.CommandLineRunner;
- import org.springframework.core.annotation.Order;
- import org.springframework.stereotype.Component;
- /**
- * mqtt发布AGV实时坐标
- */
- @Component
- @Order(2)
- @Slf4j
- public class PublishAGVInfo implements CommandLineRunner {
- private final String topic="";
- private int qos = 1;
- private MemoryPersistence persistence = new MemoryPersistence();
- private MQTTConfig mqttConfig;
- private MqttClient sampleClient;
- @Override
- public void run(String... args) throws Exception {
- // initConnect();
- }
- private void initConnect(){
- try {
- // 创建客户端
- sampleClient = new MqttClient(mqttConfig.getHOST(), mqttConfig.getClientId(), persistence);
- // 创建链接参数
- MqttConnectOptions connOpts = new MqttConnectOptions();
- // 在重新启动和重新连接时记住状态
- connOpts.setCleanSession(false);
- // 设置连接的用户名
- connOpts.setUserName(mqttConfig.getUserName());
- connOpts.setPassword(mqttConfig.getPassword().toCharArray());
- // 建立连接
- sampleClient.connect(connOpts);
- } catch (MqttException me) {
- log.error("An exception occurred when initializing the MQTT connection,msg:{}",me.getMessage());
- }
- }
- public void closeConnection(){
- try {
- // 断开连接
- sampleClient.disconnect();
- // 关闭客户端
- sampleClient.close();
- }catch (MqttException me){
- log.error("An exception occurred when the connection about MQTT was closed,msg:{}",me.getMessage());
- }
- }
- public void publishMessage(String content){
- try {
- // 创建消息
- MqttMessage message = new MqttMessage(content.getBytes());
- // 设置消息的服务质量
- message.setQos(qos);
- // 发布消息
- sampleClient.publish(topic, message);
- }catch (MqttException me){
- log.error("An exception occurred in the release information,msg:{}",me.getMessage());
- }
- }
- }
|