cuikaidong
2025-06-12 64931370717723655d4ecec4802dcdc54ec015f5
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
<template>
  <!-- 此组件没有具体的模板内容,因为它主要作为工具类使用 -->
  <div></div>
</template>
 
<script>
import * as mqtt from 'mqtt';
 
export default {
  name: 'MqttConnectionUtil',
  data() {
    return {
      client: null,
      mqttOpts: {
        keepalive: 60,
        clientId: `clientId`,
        username: 'admin',
        password: 'public',
        connectTimeout: 10 * 1000,
        path: '/mqtt'
      },
      mqttUrl: {
        head: 'ws',
        host: '192.168.1.60',
        port: 1883,
        tailPath: 'mqtt'
      }
    };
  },
  methods: {
    // 生成 MQTT 连接 URL
    generateMqttUrl() {
      return `${this.mqttUrl.head}://${this.mqttUrl.host}:${this.mqttUrl.port}/${this.mqttUrl.tailPath}`;
    },
    // 初始化 MQTT 连接
    initMqtt() {
      try {
        const opts = { ...this.mqttOpts };
        this.client = mqtt.connect(this.generateMqttUrl(), opts);
        this.client.on('connect', () => {
          console.log('MQTT 连接成功');
        });
        this.client.on('message', (topic, message) => {
          console.log(`收到消息 - 主题: ${topic}, 内容: ${message.toString()}`);
          this.$emit('messageReceived', topic, message.toString());
        });
        this.client.on('reconnect', () => {
          console.log('MQTT 正在重连');
        });
        this.client.on('error', (error) => {
          console.error('MQTT 连接错误:', error);
        });
      } catch (error) {
        console.error('MQTT 连接初始化失败:', error);
      }
    },
    // 断开 MQTT 连接
    disconnectMqtt() {
      if (this.client) {
        this.client.end();
        console.log('MQTT 连接已断开');
      }
    },
    // 订阅主题
    subscribeTopic(topic) {
      if (this.client) {
        this.client.subscribe(topic, (error) => {
          if (error) {
            console.error(`订阅主题 ${topic} 失败:`, error);
          } else {
            console.log(`成功订阅主题 ${topic}`);
          }
        });
      }
    },
    // 发布消息
    publishMessage(topic, message) {
      if (this.client) {
        this.client.publish(topic, message, (error) => {
          if (error) {
            console.error(`发布消息到主题 ${topic} 失败:`, error);
          } else {
            console.log(`成功发布消息到主题 ${topic}: ${message}`);
          }
        });
      }
    }
  },
  created() {
    this.initMqtt();
  },
  beforeDestroy() {
    this.disconnectMqtt();
  }
};
</script>
 
<style scoped>
/* 此组件没有具体的样式 */
</style>