0

I am using Eclipse Paho - Mqtt javascript library.

Trying to access onMessageArrived from outside function:

  mqttConnect(){
    var client = new Paho.MQTT.Client("wss://test.mqtt.address", "myClientId");
    this.connectionInfo = client;
    client.onConnectionLost = onConnectionLost;
    client.onMessageArrived = onMessageArrived;
    client.connect({onSuccess:onConnect});

    function onConnect() {
        client.subscribe("some/path/to/subscribe/");
    }
    function onConnectionLost(responseObject) {
        if (responseObject.errorCode !== 0) {
            console.log("onConnectionLost:"+responseObject.errorMessage);
        }
    }
    function onMessageArrived(message) {
        console.log("onMessageArrived: "+message.payloadString);
        return message.payloadString; //this does not work of course.
    }
  }

Trying to access messages from outside like:

_constract(){
  var message = mqttConnect();
  console.log(message);

}

Maybe register some global variable and put it there like this.global = message.payloadString ?

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
mr_e30
  • 3
  • 6

1 Answers1

0

You either store the message payload in a global variable so you can access it again later or you do all the processing you need from within the onMessageArrived() callback.

It has to be this way because onMessageArrived() is asynchronous, it may never be called, or it may be called many times entirely dependent on the message rate on that topic.

EDIT (example):

var client;
var lastMsg;

function connect(){
  client = new Paho.MQTT.Client("wss://test.mqtt.address", "myClientId");

  client.onConnectionLost = onConnectionLost;
  client.onMessageArrived = onMessageArrived;
  client.connect({onSuccess:onConnect});
}

function onConnect() {
  client.subscribe("some/path/to/subscribe/");
}

function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0) {
    console.log("onConnectionLost:"+responseObject.errorMessage);
  }
}

function onMessageArrived(message) {
  console.log("onMessageArrived: "+message.payloadString);
  lastMsg = message.payloadString;
}

connect();

setInterval(function() {
  document.findElementById("foo").innerHTML = lastMsg;
}, 5000);
hardillb
  • 54,545
  • 11
  • 67
  • 105