vue项目mqtt的封装与使用

1.下载安装mqtt依赖

npm install mqtt@3.0.0

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 = "";
    },

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以将MQTT封装成一个Vue插件,并将其注册到Vue实例中,这样就能够在多个组件中使用它了。 首先,我们要安装MQTT的npm包: ``` npm install mqtt --save ``` 然后,我们创建一个mqtt.js文件,将MQTT封装成一个插件: ```js import mqtt from 'mqtt' const mqttPlugin = { install (Vue, options) { Vue.prototype.$mqtt = mqtt.connect(options.host, options.options) } } export default mqttPlugin ``` 在这里,我们使用Vue的插件机制,在Vue实例中注册了一个全局的$mqtt属性,可以在任意组件中使用。 我们还需要在main.js文件中引入mqtt插件: ```js import Vue from 'vue' import App from './App.vue' import mqttPlugin from './mqtt.js' Vue.use(mqttPlugin, { host: 'mqtt://localhost:1883', options: { clientId: 'myClientId' } }) new Vue({ render: h => h(App) }).$mount('#app') ``` 在这里,我们使用Vue.use()方法来安装mqtt插件,并传递了host和options参数,以便连接到MQTT服务器。 现在,我们就可以在任意组件中使用$mqtt属性来连接和订阅MQTT主题了: ```js export default { mounted () { this.$mqtt.on('connect', () => { console.log('MQTT connected') this.$mqtt.subscribe('my/topic') }) this.$mqtt.on('message', (topic, payload) => { console.log(`Received message on topic ${topic}: ${payload.toString()}`) }) }, beforeDestroy () { this.$mqtt.end() } } ``` 在这个例子中,我们在组件的mounted()钩子中连接到MQTT服务器,并订阅了一个主题。在message事件中,我们打印出了收到的消息。 最后,在组件的beforeDestroy()钩子中,我们关闭了MQTT连接。 这样,我们就成功地封装MQTT,并能够在多个组件中使用了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值