使用 Paho.MQTT js 收发数据

2022-04-25 20:03:12 浏览数 (1)

安装依赖

代码语言:javascript复制
yarn add paho-mqtt

新建mqtt模块

代码语言:javascript复制
// utils/mqtt.ts
import Paho from "paho-mqtt";

var client: any = "";

const topicSendMsg: string = "safetyHat/data/";      // 安全帽采集(前端模拟定位数据上传)
const topicReceiveMsg: string = "safetyHat/loc/#";   // 定位数据(前端接收定位数据)
const topicAlarmMsg: string = 'fence/alarm';         // 围栏报警数据

const onMqttConnect = function (): void {
  console.log('onConnect');
  client.subscribe(topicReceiveMsg);

  const message = new Paho.Message("Hello");
  message.destinationName = topicSendMsg;
  client.send(message);
}

const initMqtt = function (): void {
  // MQTT
  const now = new Date();
  const numbers = now.getMilliseconds();

  client = new Paho.Client(
    "dev.domain.com",
    61615,
    "paho-js-"   numbers
  );

  // set callback handlers
  client.onConnectionLost = onConnectionLost;
  client.onMessageArrived = onMessageArrived;

  // connect the client

  client.connect({
    userName: "admin",
    password: "admin",
    onSuccess: onMqttConnect,
    useSSL: true,
  });

  // called when the client loses its connection
  function onConnectionLost(responseObject: any) {
    if (responseObject.errorCode !== 0) {
      console.log("onConnectionLost:"   responseObject.errorMessage);
    }
  }

  // called when a message arrives
  function onMessageArrived(message: any) {
    console.log("onMessageArrived:"   message.payloadString);
  }
};

export { topicSendMsg, topicReceiveMsg, topicAlarmMsg, client, initMqtt };

引入mqtt模块

代码语言:javascript复制
// 引入mqtt模块
import { client, initMqtt } from "@/utils/mqtt";

// 初始化mqtt
mounted() {
  initMqtt();
}

0 人点赞