Mqtt链接:

data() {
    return {
      client: null,
      }
 mounted() {
    this.initMqtt();
  },
 initMqtt() {
      if (!this.client) {
        this.client = null;
      }
      const connectUrl = "ws://地址/mqtt";
      const clientId = `app_${Math.random().toString(16).slice(3)}`;
      const mqtt = require("../../../../node_modules/mqtt/dist/mqtt.min");
      const options = {
        clean: true,
        connectTimeout: 4000,
        clientId,
        username: "admin",
        password: "密码",
      };
      this.client = mqtt.connect(connectUrl, options);
      this.client.on("connect", () => {
        console.log("连接成功....");
        this.mqttReceive();
      });
      this.client.on("error", (err) => {
        console.log("err=>", err);
        this.client.end();
      });
    },

## mqtt发送主题

    mqttReceive() {
      const topic = `/device/wavve/vital/sign/${this.deviceSn}`;
      this.client.subscribe(topic, (err) => {
        if (!err) {
          console.log("subscribe success!已发送主题", topic);
        } else {
          console.log("err", err);
        }
      });
      this.client.on("message", (topic, message) => {
        // console.log(message, "接收的报文");
        const data = JSON.parse(message.toString());
        const parsedData = JSON.parse(data);
        const body = parsedData.heartBpm;
        // console.log(body, "parsedData");
        this.heartRate = parsedData.heartBpm; // 更新 heartRate 值
        this.callheartRate = parsedData.breathBpm; // 更新 heartRate 值
        this.state = parsedData.state;
      });
    },
    
   //关闭mqtt
    disconnectMqtt() {
      if (this.client) {
        this.client.end();
        console.log("MQTT 关闭");
      }
    },
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐