mqtt实现多个topic订阅头,并发布不同topic以及信息

2,018 阅读1分钟

mqtt实现多个topic订阅头,并发布不同topic以及信息

新建一个mqtt.js对mqtt的方法进行封装,内容如下

import mqtt from 'mqtt';

class MQTTWrapper {
  constructor(options) {
    this.client = mqtt.connect(options.brokerUrl, options.options);
    this.subscriptions = {};
    this.client.on('connect', this.onConnect.bind(this));
    this.client.on('message', this.onMessage.bind(this));
  }

  onConnect() {
    console.log('Connected to MQTT broker');
    Object.keys(this.subscriptions).forEach((topic) => {
      this.client.subscribe(topic);
    });
  }

  onMessage(topic, message) {
    if (this.subscriptions[topic]) {
      this.subscriptions[topic](message.toString());
    }
  }

  subscribe(topic, callback) {
    this.subscriptions[topic] = callback;
    if (this.client.connected) {
      this.client.subscribe(topic);
    }
  }

  unsubscribe(topic) {
    delete this.subscriptions[topic];
    if (this.client.connected) {
      this.client.unsubscribe(topic);
    }
  }

  publish(topic, message) {
    if (this.client.connected) {
      this.client.publish(topic, message);
    }
  }

  end() {
    this.client.end();
  }
}

export default MQTTWrapper;

在需要使的组件里面使用

created() {
    const options = {
      brokerUrl: 'mqtt://your-broker-url', // Specify your MQTT broker server address
      options: {
        // You can add other MQTT connection options here, such as clientId, username, password, etc.
      },
    };

    this.mqttClient = new MQTTWrapper(options);

    const topic1 = 'your/topic/1';
    const topic2 = 'your/topic/2';

    this.mqttClient.subscribe(topic1, (message) => {
      this.topic1Content = message;
    });

    this.mqttClient.subscribe(topic2, (message) => {
      this.topic2Content = message;
    });

    this.mqttClient.publish(topic1, 'Hello from topic 1!');
    this.mqttClient.publish(topic2, 'Greetings from topic 2!');
  },
  beforeDestroy() {
    this.mqttClient.end();
  },