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
101
102
103
104
105
106
107
108
109
<template>
  <div>{{ title }}</div>
</template>
 
<script>
import * as mqtt from 'mqtt'
import { getAction } from '@/api/manage'
 
 
export default {
  name: 'MqttIot',
  data() {
    return {
      client: '',
      clientCount: 0,
      topic: [],
      title: '',
      receivedMessage: null,  // 用于存储接收到的消息
      mqttOpts: {
        keepalive: 60,
        clientId: 'clientId-' + Math.random().toString(16).substr(2, 8),
        username: '',
        password: '',
        connectTimeout: 10 * 1000,
        path: '/mqtt'
      },// 连接配置
      mqttUrl: {
        head: 'ws', // 必须是 ws 或 wss (mqtt:// 或 mqtts:// 必须让后端开放websocket服务)
        host: '', // ip地址
        port: 8083, // 服务端口
        tailPath: 'mqtt' // 服务路径
      },
      url: {
        subscribe: '/equipment/subscribe',
        queryById: '/serve/deploy/mqtt/queryById'
      }
    }
  },
  props: ['serverId'],
  methods: {
 
    //创建连接
    initMqtt() {
      // 根据服务器id获取mqtt连接参数
      getAction(this.url.queryById, { id: this.serverId }).then((res) => {
        if (res.success && res.result != null) {
          this.mqttUrl.host = res.result.address
          // this.mqttUrl.port = res.result.port
          this.mqttOpts.username = res.result.userName
          this.mqttOpts.password = res.result.userPassword
          let opts = JSON.parse(JSON.stringify(this.mqttOpts))
          this.client = mqtt.connect(`${this.mqttUrl.head}://${this.mqttUrl.host}:${this.mqttUrl.port}/${this.mqttUrl.tailPath}`, opts)
          this.client.on('connect', this.handleConnect)
          this.client.on('message', this.handleMessage)
          this.client.on('reconnect', this.handleReconnect)
          this.client.on('error', this.handleError)
        }
      })
    },
    //断开连接
    disconnectMqtt() {
      this.client.end()
      console.log('mqtt_断开成功')
    },
    handleConnect() {
      console.log('mqtt_连接成功')
      // 查询订阅主题
      getAction(this.url.subscribe, { id: this.serverId }).then((res) => {
        if (res.success) {
          this.client.subscribe(res.result)
        }
      })
    },
    handleMessage(topic, message) {
      // 区分虚设备实实设备
      this.receivedMessage = JSON.parse(message.toString())
      if (topic.split('/')[2] === 'ActualDevices') {
        this.$bus.$emit('solid-iot-topic', message.toString())
      } else {
        this.$bus.$emit('empty-iot-topic', message.toString())
      }
      this.title = this.receivedMessage.msg
    },
 
    handleReconnect(error) {
      console.log(`正在第${this.clientCount}重连`, error)
      this.clientCount++
      if (this.clientCount >= 10) {
        this.client.end()
      }
    },
 
    handleError(error) {
      console.log('连接失败', error)
    },
 
    /**
     * MQTT实现发送消息
     * @param: topic: 主题
     * @param: message: 消息体
     **/
    mqttPublish(topic, message) {
      this.client.publish(topic, JSON.stringify(message))
    }
  },
}
</script>
<style>
</style>