1
votes

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);
  }
}
1
It seems there is no way to achieve it there. I'm using a switch case currently.Mr.

1 Answers

1
votes

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