5

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.

2 Answers 2

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
    Commented Jul 4, 2019 at 16:15
1

i found different solution to this in python

client.py

 class Messages(threading.Thread):
    def __init__(
        self,
        clientname,
        broker="127.0.0.1",
        pub_topic="msg",
        sub_topic=[("msg", 0)],
    ):
        super().__init__()
        self.broker = broker
        self.sub_topic = sub_topic
        self.pub_topic = pub_topic
        self.clientname = clientname
        self.client = mqtt.Client(self.clientname)
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_subscibe = self.on_subscribe
        self.received = {}
        self.topicTemp = "" <==== define temporary topic name

    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("Server Connection Established")
        else:
            print("bad connection Returned code=", rc)
        self.client.subscribe(self.sub_topic)

    def on_subscribe(self, client, userdata, mid, granted_qos):
        print("Subscription complete")

    def on_message(self, client, userdata, msg):
        if self.topicTemp != msg.topic:  <=== compare incoming topic name
            self.received[msg.topic] = {  <=== create new element of received dict
                "topic": msg.topic,
                "payload": str(msg.payload.decode()),
            }
        self.topicTemp = msg.topic <== store handlede topic to compare next one

    def begin(self):
        print("Setting up connection")
        self.client.connect(self.broker)
        self.client.loop_start()
        # self.client.loop_forever()

    def end(self):
        time.sleep(1)
        print("Ending Connection")
        self.client.loop_stop()
        self.client.disconnect()

    def send(self, msg, topic=None):
        if topic is None:
            topic = self.pub_topic
        self.client.publish(topic, msg)

    def get(self, msg, topic=None):
        if topic is None:
            topic = self.sub_topic[0]
        self.client.subscribe(topic, msg)
        # self.send(msg, topic)


def main():
    remote = Messages(clientname="PC", broker="127.0.0.1")
    remote.begin()


if __name__ == "__main__":
    main()

function.py

    from mqtt_client_test import Messages
import time

remote = Messages(
    clientname="Camera",
    broker="127.0.0.1",
    pub_topic="pc/camera",
    sub_topic=[("pc/camera", 0), ("commands/detect", 1)],
)
remote.begin()
while True:
    msg = remote.received
       # print(msg)
    if "commands/detect" in msg:
        print("command", msg["commands/detect"]["payload"])
    if "pc/camera" in msg:
        print("camera", msg["pc/camera"]["payload"])
    time.sleep(1)
    

Now you can get payloads from different topics in one on_message function and can extract how you want to use somewhere else...

Your Answer

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

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