4

I have created a Publisher Script using Paho MQTT JavaScript API which publishes values to two topics MyHome/Temp and MyHome/Hum. The script is running successfully and publishing data to CloudMQTT broker. In my Subscriber script I have subscribed to these two topics and printing them in Console as following:

function onConnect() {
  console.log("onConnect");
  client.subscribe("MyHome/Temp");
  client.subscribe("MyHome/Hum");
}

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

It is printing both the topic names and corresponding values. Now I want to extract the values of both topics using message.payloadString and store in variable as following:

function onMessageArrived(message) { 
  var temp = message.payloadString;
  var hum = message.payloadString;
  ...
}

But I am getting only on value in both variable i.e. the value of last topic 'hum'. Can anyone please help me solving this.

1 Answer 1

4

onMessageArrived will be called separately for each message that arrives so if the payload only contains one value then you will only be able to get one value at a time.

You need to include a if statement in the onMessageArrived callback to determine which topic the message arrived on and then set the respective value.

1
  • Thanks @hardillb you are exactly right. I declared var temp and var hum as global variables the that the value should remain in temp when the value in hum is being stored, and added the if statement to set the respective values. Here's my code<br/> var temp = ""; var hum = ""; ... function onMessageArrived(message) { if(message.destinationName == "MyHome/Temp"){ temp = message.payloadString; } if(message.destinationName == "MyHome/Hum"){ hum = message.payloadString; } ... }
    – tim3in
    Jul 4, 2019 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.