[MQTT] Web 连接 EMQX,并发布和订阅主题

简单封装

file:[Terminal]
npm install mqtt

# 或使用 pnpm

pnpm install mqtt

# 或使用 yarn

yar add mqtt

如果你的项目是 TS 项目,需要在 tsconfig.json 中添加 allowJs: true 字段。

file:[src/utils/mqtt.ts]
// 导入类型
import type { MqttClient } from "mqtt";
// 导入 min.js,而非 mqtt
import * as mqtt from "mqtt/dist/mqtt.min.js";

export function connect(): MqttClient {
  const mqttClient = mqtt.connect("ws://localhost:8083/mqtt", {
    clean: false,
    connectTimeout: 4000,
    clientId: "webclient",
    username: "webclient",
    password: "123456"
  });

  return mqttClient;
}

// 开启
export function start(client: MqttClient, onMessage: (msg: string) => void) {
  // 连接之后订阅一个主题
  client.on("connect", function () {
    client.subscribe("command", function (err) {});
  });

  // 收到 emqx 服务器发送的主题,调用回调函数并把消息带出去,注意消息需要调用 toString
  client.on("message", function (topic, message) {
    console.log(JSON.parse(message.toString()));
    onMessage(JSON.parse(message.toString()));
  });
}

// 发布主题
export function publish(client: MqttClient, data: { topic: string; msg: string }) {
  client.publish(data.topic, data.msg);
}

在组件中使用

file:[src/views/Index.vue]
import { connect, start, publish } from "@/emqx-utils";
import { onMounted } from "vue";

const nowCGQState = ref();
const emqxClient = connect();
const mqttCommand = ref("Num1Ledon");

onMounted(() => {
  start(emqxClient, msg => (nowCGQState.value = msg));
})

function pushCommand() {
  publish(emqxClient, { topic: "command", msg: mqttCommand.value });
}
file:[src/views/Index.vue]
<template>
  <el-input v-model="mqttCommand" />
  <el-button @click="pushCommand">发送主题</el-button>
</template>
posted @ 2023-06-23 01:49  Himmelbleu  阅读(21)  评论(0编辑  收藏  举报