mqtt+vue2+js

[写在前面]
官网:https://github.com/mqttjs/MQTT.js
...等等再写...

[版本明细]
"vue": "2.6.10",
"vue-router": "3.0.6",
"vuex": "3.1.0"
"mqtt": "^5.8.1",
"crypto-js": "^4.2.0",
"electron": "^13.6.9",
"electron-devtools-installer": "^3.1.0",

[vue.config.js]
mqtt内部使用 ES6+ 的语法,使用过程中可能存在无法解析的情况,导致项目启动报错,需要在‘vue.config.js’中增加配置 transpileDependencies: ["mqtt"]

Ps. transpileDependencies 是一个Vue CLI 的配置选项,用于制定需要被转译的依赖包。在Vue项目中,有些依赖包可能是用了ES6+的语法,而一些低版本的浏览器不支持这些语法,因此需要将这些依赖包转译成ES5语法,以便在低版本浏览器中正常运行。

[接口数据]

  1. getMqttConnectInfo
    返回值:
    data: {
    host: "mqtt.xxxx.net", // "mqtt域名",
    port: 8084, // "mqtt端口",
    secretKey: "mmmmmmm", //"mqtt密钥,mqtt密码 = md5(clientId,secretKey) ",
    timestamp: 1758796, // "mqtt服务器时间戳",
    token: "tokentokentoke token", //"clientid = token|sighmethod=md5,timestamp=nowdate ",
    topic: "/message/yyyy", //"订阅主题",
    username: "username", //"mqtt用户名",
    },

[开始啦]

mqtt.js:

import mqtt from "mqtt";
import crypto from "crypto-js";
class MQTT {
  url = ""; // mqtt地址
  topic = ""; //
  token = ""; //
  secretKey = "";
  username = "";
  password = ""; //密码
  // 初始化类实例
  constructor(params) {
    console.log("mqtt实例", params);
    this.topic = params.topic; // 订阅的topic
    this.token = params.token;
    this.secretKey = params.secretKey;
    this.url = params.url;
    this.username = params.username;
    this.password = params.password;
  }

  //初始化mqtt
  init(config) {
    const connectUrl = this.url || "wss://mqtt.djcps.com:8084/mqtt";
    const token = this.token; //token
    const username = this.username; // 用户名
    const secretKey = this.secretKey; //密钥

    //生成clientid (注意时间戳使用当前时间的,不要使用后端返回的,会导致密码失败)
    var clientId = token + "|" + "signmethod=hmacmd5,timestamp=" + Date.now();
    //生成password (这里使用HmacMD5加密, 没有使用普通的md5)
    var password = crypto.HmacMD5(clientId, secretKey).toString();

    const options = {
      clean: true,
      protocolVersion: 4,
      protocolId: "MQTT",
      rejectUnauthorized: false,
      connectTimeout: config.connectTimeout,
      reconnectPeriod: config.reconnectPeriod,
      clientId: clientId,
      username: username,
      password: password,
      keepalive: 60,
      // 其他
      // protocol: "ws",
      // host: this.url,
      // ws: 8084,
      // wss: 8084,
      // port: 8008,
      // endpoint: "/mqtt",
    };

    // const connectUrl = `${options.protocol}://${options.host}:${options.port}${options.endpoint}`;
    // 使用地址链接
    this.client = mqtt.connect(connectUrl, options);
    // 消息处理
    this.client.on("message", (topic, message) => {
      let mqData = JSON.parse(message.toString());
      console.log("收到消息", topic, message, mqData);
      //接收消息
      if (config.messageCallback) {
        config.messageCallback(topic, mqData);
      }
    });
    // 重连处理
    this.client.on("reconnect", (error) => {
      console.log("正在重连:", error);
    });
    // 链接失败
    this.client.on("error", (error) => {
      console.log("链接失败", error);
    });
  }
  //取消订阅
  unsubscribes() {
    this.client.unsubscribe(this.topic, (error) => {
      if (!error) {
        console.log("取消订阅成功");
      } else {
        // console.log('取消订阅失败');
      }
    });
  }
  //连接
  link() {
    this.client.on("connect", (con) => {
      let qosValue = this.qos;
      this.client.subscribe(this.topic, { qosValue }, (error, res) => {
        if (!error) {
          console.log("订阅成功");
        } else {
          console.log("订阅失败");
        }
      });
    });
  }
  // // 发送信息
  // SendMessage(topic, sendMsg) {
  //   let options = this.qos;
  //   this.client.publish(
  //     "rscu/sensor/exterior/up/id",
  //     sendMsg,
  //     options,
  //     (err, a) => {
  //       if (!err) {
  //         console.log("发送信息成功");
  //         // this.$message.success("发送信息成功");
  //       } else {
  //         console.log("发送信息失败");
  //       }
  //     }
  //   );
  // }
  // //收到的消息
  // get(callback) {
  //   this.client.on("message", callback);
  // }
  //结束链接
  over() {
    this.client.end();
    console.log("结束链接");
  }
}
export default MQTT;

使用:

import MQTT from "./mqtt";

  created() {
    this.startMqtt();
    this.scanner = new Scanner();
    console.log(this.scanner);
    this.scanner.listener(this.scannerAdd);
  },
  destroyed() {
    this.endMqtt();
    this.PublicMqtt = null;
    this.scanner.end();
  },

  methods: {
    // 连接mqtt
    startMqtt() {
      const _machineInfo = JSON.parse(localStorage.getItem("machineInfo"));
      Api.get_mqttConnectInfoNoAuth(_machineInfo.deviceId)
        .then((res) => {
          console.log("请求token", res);
          if (res.success) {
            const mqttConfig = res.data;
            mqttConfig.url =
              "wss://" + mqttConfig.host + ":" + mqttConfig.port + "/mqtt";
            //设置订阅地址
            this.PublicMqtt = new MQTT(mqttConfig);
            //初始化mqtt
            this.PublicMqtt.init({
              reconnectPeriod: 5000, //重连时间间隔
              connectTimeout: 5000,
              messageCallback: this.getMqttMessage, // 接收消息
            });
            //链接mqtt
            this.PublicMqtt.link();
          } else {
            console.log("未连接芯片");
          }
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {});
    },
    getMqttMessage(topic, message) {
      console.log("接收到消息", topic, message);
    },
    // 断开链接
    endMqtt() {
      if (this.PublicMqtt) {
        this.PublicMqtt.unsubscribes();
        this.PublicMqtt.over();
      }
    },
    // 发送信息 监测有没有链接 没有弹框
    // send(topic, message) {
    //   console.log("send方法被触发", topic, message);
    //   if (this.PublicMqtt) {
    //     let mqttPayload = JSON.parse(message);
    //     mqttPayload.dynamicType = "";
    //     message = JSON.stringify(mqttPayload);
    //     this.PublicMqtt.SendMessage(topic, message);
    //   } else {
    //     this.$message.error("尚未连接");
    //   }
    // },
  }

其他

  1. 加密方式有 js-md5 ts-md5 crypto.HmacMD5,这里使用最后一个
//js使用
var key = md5('hello');
console.log("加密后:"key) //加密后:5d41402abc4b2a76b9719d911017c592

//ts使用
var key = Md5.hashStr('hello');
console.log("加密后:"key) //加密后:5d41402abc4b2a76b9719d911017c592

crypto.HmacMD5(clientId, secretKey).toString();
  1. 获取到mqtt消息之后,需要通过 JSON.parse 进行处理,直接打印消息无法获取
let mqData = JSON.parse(message.toString());
  1. 如果有如下报错, 可能是生成密钥的时候,时间戳不是当前时间戳导致的
mqtt Connection refused: Bad username or password
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容