PublishAGVInfo.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package com.ruoyi.tianao.init;
  2. import com.ruoyi.tianao.config.MQTTConfig;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.eclipse.paho.client.mqttv3.MqttClient;
  5. import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
  6. import org.eclipse.paho.client.mqttv3.MqttException;
  7. import org.eclipse.paho.client.mqttv3.MqttMessage;
  8. import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  9. import org.springframework.boot.CommandLineRunner;
  10. import org.springframework.core.annotation.Order;
  11. import org.springframework.stereotype.Component;
  12. /**
  13. * mqtt发布AGV实时坐标
  14. */
  15. @Component
  16. @Order(2)
  17. @Slf4j
  18. public class PublishAGVInfo implements CommandLineRunner {
  19. private final String topic="";
  20. private int qos = 1;
  21. private MemoryPersistence persistence = new MemoryPersistence();
  22. private MQTTConfig mqttConfig;
  23. private MqttClient sampleClient;
  24. @Override
  25. public void run(String... args) throws Exception {
  26. // initConnect();
  27. }
  28. private void initConnect(){
  29. try {
  30. // 创建客户端
  31. sampleClient = new MqttClient(mqttConfig.getHOST(), mqttConfig.getClientId(), persistence);
  32. // 创建链接参数
  33. MqttConnectOptions connOpts = new MqttConnectOptions();
  34. // 在重新启动和重新连接时记住状态
  35. connOpts.setCleanSession(false);
  36. // 设置连接的用户名
  37. connOpts.setUserName(mqttConfig.getUserName());
  38. connOpts.setPassword(mqttConfig.getPassword().toCharArray());
  39. // 建立连接
  40. sampleClient.connect(connOpts);
  41. } catch (MqttException me) {
  42. log.error("An exception occurred when initializing the MQTT connection,msg:{}",me.getMessage());
  43. }
  44. }
  45. public void closeConnection(){
  46. try {
  47. // 断开连接
  48. sampleClient.disconnect();
  49. // 关闭客户端
  50. sampleClient.close();
  51. }catch (MqttException me){
  52. log.error("An exception occurred when the connection about MQTT was closed,msg:{}",me.getMessage());
  53. }
  54. }
  55. public void publishMessage(String content){
  56. try {
  57. // 创建消息
  58. MqttMessage message = new MqttMessage(content.getBytes());
  59. // 设置消息的服务质量
  60. message.setQos(qos);
  61. // 发布消息
  62. sampleClient.publish(topic, message);
  63. }catch (MqttException me){
  64. log.error("An exception occurred in the release information,msg:{}",me.getMessage());
  65. }
  66. }
  67. }