question_1
question_1

Reputation: 112

Paho Javascript MQTT subscribe to multiple topics

Is it possible to use a similar concept (in javascript) with the message_callback_add used in paho python to use multiple callbacks when the client subscribes to multiple topics? I have seen the use of if conditions in onMessageArrived() but I was wondering whether a more efficient and clean way exists?

var mqtt;                           // MQTT variable/object
var reconnectTimeout = 5000;        // 5 seconds for the reconnectTimeout
var host="localhost";               // MQTT bridge IP
var port=8083;                      // MQTT bridge port 
MQTTconnect();                      // Initialise the MQTT connections

function MQTTconnect(){
  console.log("mqtt connecting to " + host + ":" + port);
  mqtt = new Paho.MQTT.Client(host, port, "client_test");
  var options = {
    timeout: 100,
    onSuccess: onConnect,
    onFailure: onFailure,
  };
  mqtt.onMessageArrived = onMessageArrived;
  mqtt.connect(options); // connect
}

function onConnect(){
  console.log("Mqtt Connected - Subscribe to the topics");
  mqtt.subscribe("topic1/a");
  mqtt.subscribe("topic2/b");
}
            
function onFailure(message){
  console.log("Connection attempt to MQTT " + host + " failed");
  setTimeout(MQTTconnect, reconnectTimeout);
}

function onMessageArrived(msg){
  if (msg.destinationName == "topic1/a"){
    console.log("Topic1: ", msg.payloadString);
  }
  else if (msg.destinationName == "topic2/b"){
    console.log("Topic2: ", msg.payloadString);
  }
}

Upvotes: 1

Views: 1370

Answers (2)

VocoJax
VocoJax

Reputation: 1549

The library may not have it, but make your own callback logic! Here is a pretty looking solution:

import EventEmitter from 'events';
const emitter = new EventEmitter();

client.subscribe('my_topic_1');
client.subscribe('my_topic_2');
client.onMessageArrived = onMessage;

function onMessageArrived(message) {
   emitter.emit(message.topic, message.payloadString);
}

function subscribe(event, callback) {
   emitter.addListener(event, callback);
}

function unsubscribe(event, callback) {
   emitter.removeListener(event, callback);
}

subscribe('my_topic_1', (string) => {
   console.log('only my_topic_1 messages', string);
});

Upvotes: 0

hardillb
hardillb

Reputation: 59608

No, there is only one callback from all messages in the JavaScript.

The only option is to check the topic and branch as needed in the onMessageArrived callback

Upvotes: 2

Related Questions