window.MQTT_URL = 'ws://xx.xxx.xx.xx:8083/mqtt'
<template>

</template>

<script setup>
import * as mqtt from "mqtt/dist/mqtt.min";
const emit = defineEmits();
import {onBeforeUnmount} from "vue";
const mqttfalg = ref(true)
const message = ref('连接mqtt')
const mqttvalue = ref('mqtt接收的值')
const options = ref({
  connectTimeout: 100, //超时时间
  clientId: "xx_yeweiyi_" + Math.random().toString(16).substring(2, 8), //id
  cleanSession: true,
  keepAlive: 20, //心跳值,心跳值太大可能会连接不成功
})
const client = ref(null)
defineExpose({
  subscribe
})

function connect() {
  if (mqttfalg.value) {
    console.log("开始链接")
    // 默认连接的协议
    client.value = mqtt.connect(
        window.MQTT_URL,
        options.value
    );

    client.value.on("connect", (e) => {
      message.value = `连接成功${e}`;
      // 设置mqttFlag为false,确保connect方法只执行一次
      mqttfalg.value = false;
      console.log("连接成功", e);
    });

    client.value.on("reconnect", (error) => {
      console.log("正在重连", error);
    });

    client.value.on("disconnect", (error) => {
      console.log("服务器断开", error);
    });

    client.value.on("close", (error) => {
      client.value.end();
    });

    client.value.on("error", (error) => {
      console.log("连接出错", error);
    });

    client.value.on("message", (topic, message) => {
      mqttvalue.value = JSON.parse(message.toString());
      emit('update:getTankInfo', mqttvalue.value);
    });
  }
}
//订阅
function subscribe(mqttDeviceName){
  if(mqttDeviceName){
    setTimeout(() => {
      connect();
      // 订阅的设备配置
      client.value.subscribe(
          window.MQTT_TOPIC.replaceAll('%mqttDeviceName%', mqttDeviceName),
          {qos: 1},
          (error) => {
            if (error) {
              connect();
              console.log(error);
            } else {
              console.log("订阅成功");
            }
          }
      );
    }, 100);
  } else {
    console.log("此设备未绑定监控设备")
  }
}
// 断开链接
function disconnect() {
  if (client.value) {
    client.value.end();
    console.log("断开连接");
  }
}
// 断开链接
function breakOff() {
  client.value.end();
  console.log("断开");
}
// 销毁组件时断开连接
onBeforeUnmount(() => {
  console.log("销毁组件时断开连接");
  disconnect();
})

// connect();
</script>

<style scoped>

</style>

更多推荐