前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用 Paho.MQTT js 收发数据

使用 Paho.MQTT js 收发数据

作者头像
4O4
发布2022-04-25 20:03:12
1.5K0
发布2022-04-25 20:03:12
举报
文章被收录于专栏:404404

安装依赖

代码语言: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();
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-03-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装依赖
  • 新建mqtt模块
  • 引入mqtt模块
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档