vue组件封装mqtt

4,357 阅读2分钟

vue组件封装mqtt

父组件通过传值给子组件,子组件调用不同的mqtt主题,
子组件接受mqtt推送的消息后调用父组件的方法并且传值给父组件。父组件便能取到mqtt的实时数据

1、index.html 引入mqtt.js

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <script src="./static/tools//mqttws31.js"></script> <!-- 引入mqttws31.js  -->
    <title>********</title>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

2、封装mqtt通信组件

<template></template>

<script>
import * as tool from "../../utils/tools";
export default {
  name: "MqttClient",
  data() {
    return {
      client: null,
      count: {
        waterIn: 0
      }
    };
  },
  methods: {
    // 建立新连接
    buildConnect(e) {
      let clientParams = {
        hostname: "XXXX",
        port: 443,
        clientId: "myclientid_" + tool.UUID(),
        userName: "XXXX",
        password: "XXXX"
      };

      // 建立客户端实例
      var options = {
        useSSL: true,
        userName: clientParams.userName,
        password: clientParams.password,
        onSuccess: () => {
          this.clientSuccess(e);
        },
        onFailure: message => {
          this.clientFailure(message);
        }
      };
      if (this.client !== null) {
        this.client.disconnect();
        return this.client.connect(options);
      }
      this.client = new Paho.MQTT.Client(
        clientParams.hostname,
        clientParams.port,
        "/mqtt/ws",
        clientParams.clientId
      );

      this.client.connect(options); // 连接服务器并注册连接成功处理事件
      this.client.onConnectionLost = responseObject => {
        // this.onConnectionLost(responseObject, options); // 注册连接断开处理事件
        if (responseObject.errorCode != 0) {
          console.log("连接已断开");
          this.count.waterIn++;
          if (this.count.waterIn >= 6) {
            setTimeout(() => {
              this.client.connect(options);
            }, 120000);
          } else {
            setTimeout(() => {
              if (this.client != null) {
                this.client.connect(options);
              }
            }, 2000);
          }
        } else {
          console.log("异常:连接丢失" + responseObject.errorMessage);
          this.client.connect(options);
        }
      };
      this.client.onMessageArrived = data => {
        this.onMessageArrived(data); // 注册消息接收处理事件
      };
    },
    // mqtt连接成功
    clientSuccess(e) {
      console.log("连接成功");
      console.log(e);
      // this.$emit("messageArrived", "连接成功");
      this.client.subscribe(e); // 订阅主题
    },
    // mqtt连接失败
    clientFailure(e) {
      console.log("连接失败");
      console.log(e);
    },
    // 接收消息事件
    onMessageArrived(message) {
      console.log("收到消息:" + message.payloadString);
      this.$emit("messageArrived", JSON.parse(message.payloadString));
    },
    // 断开mqtt连接
    disconnect() {
      try {
        console.log("断开");
        if (this.client) {
          this.client.disconnect();
          this.client = null;
        }
      } catch (e) {
        console.log(e);
      }
    }
  }
};
</script>

<style>
</style>

3、在需要的组件中引入

  • 一个mqtt连接
<template>
  <div>
    <!-- mqtt通信组件 -->
   <mqtt-client @messageArrived="messageArrived" ref="mqtt" />
  </div>
</template>
<script>
import MqttClient from "@/views/Core/MqttClient";
export default {
  components: {
    MqttClient
  },
  data () {
    return {
    }
  },
  mounted () {
    this.watchmqtt() // 建立mqtt通信
  },
  beforeDestroy () {
    this.disconnect() // 关闭页面断开mqtt连接
  },
  methods: {
   //mqtt连接
    watchmqtt(theme) {
      this.$nextTick(() => {
        this.$refs.mqtt.buildConnect(theme);
      });
    },
    //接收消息
    messageArrived(res) {
      console.log(res);
      this.handledata(res);
        console.log(this.alldata);
        console.log(res);
        this.nowdatetime = tool.getdate(res.timestamp);
        console.log(this.nowdatetime);
    },
    //断开连接
    disconnect() {
      this.$refs.mqtt.disconnect();
    },
  }
}
</script>

<style>
</style>

  • 多个mqtt连接

通过ref属性同时调用和取值

 <!--a- mq -->
    <mqtt-client @messageArrived="personMqttData" ref="mqttClientA" />
    <!-- b- mq -->
    <mqtt-client @messageArrived="signInMqttData" ref="mqttClientB" />
    <!-- c-mq -->
    <mqtt-client @messageArrived="problemMqttData" ref="mqttClientC" />