Search code examples
javascripthandlermqttslashpaho

MQTT Paho Javascript - Is it possible to define a handlerfunction per subscription?


I am making a web application with MQTT Paho Javascript (mqttws31.js).

in my onMessageArrived function I now define what message arrived by the following code:

    var topic = message.destinationName;
    var message = message.payloadString;
    var n = topic.lastIndexOf('/');
    var result = topic.substring(n + 1);
    switch(result){
      case "register":{
        //registerhandler
      }
      break;
      case "data":{
        //datahandler
      }
      break;
      default:{
        alert("wrong topic");
      }
    };

Is there a better way to check the topic?

Is it possible to define a messageArrived function per subscription? The only way I know to define the messageArrived is before the client.connect function. And the only way I know to subscribe is after the connection to do client.subscribe.

It would be very handy to define for example: client.subscribe("registertopic", registerhandlerfunction);

What can I do?


Solution

  • No, the client api doesn't provide this capability.

    You have a couple options. Either do as you are doing; hard code a series of if/then/elses or switch/cases. Or you could quite easily add your own wrapper to the client library that provides it a more generic capability.

    For example, the following untested code:

    var subscriptions = [];
    function subscribe(topic,callback) {
        subscriptions.push({topic:topic,cb:callback});
        mqttClient.subscribe(topic);
    }
    
    mqttClient.onMessageArrived = function(message) {
        for (var i=0;i<subscriptions.length;i++) {
            if (message.destinationName == subscriptions[i].topic) {
                subscriptions[i].cb(message);
            }
        }
    }
    

    Note, this assumes you only subscribe to absolute topics - ie without wildcards. If you use wildcards, you'd have to do some regular expression matching rather than the == test this code uses.