<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>
|