1、下载安装mqtt依赖(版本不要太高推荐4.1.0以下)
npm install mqtt@x.x.x
2.封装mqttHandler.js工具文件
import mqtt from "mqtt";
import Vue from 'vue'
var vm = new Vue();
class mqttHandle {
constructor(subscribe) {
this.connect = {
host: vm.mqttHost,
port: vm.mqttPort,
endpoint: "/mqtt",
clean: true, // 保留会话
cleanSession: true,
connectTimeout: 7000, // 超时时间
reconnectPeriod: 7000, // 重连时间间隔
// 认证信息
clientId: Number(new Date()).toString(),
username: "emqx_t",
password: "emqx_t",
}
this.subscription = {
topic: subscribe, //需要传入数组的包含订阅的名称
qos: 2,
}
this.mqttClient = null;
}
/**
* 创建链接
* @returns client
*/
createConnect() {
//配置链接
const { host, port, endpoint, ...options } = this.connect;
const connectUrl = `ws://${this.connect.host}:${this.connect.port}${this.connect.endpoint}`;
try {
this._client = mqtt.connect(connectUrl, options);
} catch (error) {
console.log("mqtt.connect error", error);
}
this._client.on("connect", () => {
console.log("Connection succeeded!");
});
this._client.on('reconnect', (error) => {
console.log('正在重连', error)
})
this._client.on("error", (error) => {
console.log("Connection failed", error);
});
//配置topic
const { topic, qos } = this.subscription;
this._client.subscribe(topic, { qos: qos }, (error, res) => {
if (error) {
console.log("Subscribe to topics error", error);
return;
}
this.subscribeSuccess = true;
// console.log("Subscribe to topics res", res[0].qos, res[0].topic);
});
this.mqttClient = this._client;
return this.mqttClient;
}
}
export default mqttHandle;
3.在要订阅mqtt的页面引入mqttHandler.js
// mqtt
import mqttHandle from "../../../utils/mqttHandle";
4.声明订阅mqtt的时候要用到的变量
var mqtt; //mqtt 处理对象(全局变量)
var client;
var topicSends; //订阅的topic 例如:["Time1", "EngineMain1", "Console1", "Location1"]
// 在data中声明接收mqtt返回数据的变量
data(){
return{
receiveNews: "",
}
}
5.需要订阅mqtt的时候调用订阅mqtt的方法,一般都是进页面就触发,所以一般都写在mounted()方法里。
mounted(){
this.createMqtt();
}
methods:{
/** 创建mqtt */
createMqtt() {
//创建链接,接收数据
mqtt = new mqttHandle(topicSends);
client = mqtt.createConnect();
client.on("message", (topic, message) => {
//数据分类
try {
this.receiveNews = this.receiveNews.concat(message);
this.realInfo(topic, this.receiveNews);
} catch (error) {}
});
},
}
6.停止订阅mqtt的时候调用以下方法
//停止订阅mqtt
disConnect() {
if (client != null) {
client.unsubscribe(topicSends);
client = null;
}
},
7.同时订阅多个topic时,可以调用以下方法
/** 实时数据分类 */
realInfo(topic, resInfo) {
switch (topic) {
// 接收时间
case "Time1":
case "Time2":
case "Time3":
try {
this.currentTime = resInfo;
} catch (error) {}
break;
// 树结构
case "EngineMain1":
case "EngineMain2":
case "EngineMain3":
break;
// 控制台输出
case "Console1":
case "Console":
case "Console2":
case "Console3":
try {
let arr = JSON.parse(resInfo);
this.$refs.rightTabRef.updateInfo(arr);
} catch (error) {}
break;
// 模型
case "Location1":
case "Location2":
case "Location3":
try {
this.modelList = JSON.parse(resInfo);
this.modelList.forEach(item => {
// 模型节点
if (item.entityType != 16) {
if (this.$refs.cesiumRef.loadModel)
this.$refs.cesiumRef.loadModel(item, false);
} else {
// 信号节点
this.checkedModelList.forEach(item1 => {
// 选中的信号节点
if (item1.ID == item.id) {
// x轴数据,最多存放20条数据
if (this.xData.length > 20) {
this.xData.splice(0, 1);
}
this.xData.push(item.tagTwo);
let findindex = this.titleList.findIndex(
m => m == item1.label
);
if (findindex == -1) {
this.titleList.push(item1.label);
let ydata = {
name: item1.label,
type: "line",
stack: "Total",
data: [item.tagOne]
};
this.yData.push(ydata);
} else {
this.yData
.filter(s => s.name == item1.label)[0]
.data.push(item.tagOne);
let data = this.yData.filter(
s => s.name == item1.label
)[0].data;
if (data.length > 260) {
this.yData
.filter(s => s.name == item1.label)[0]
.data.splice(0, 1);
}
}
}
});
}
});
this.initEcharts();
} catch (error) {}
break;
}
this.receiveNews = "";
},