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.

tim3in
  • 377
  • 3
  • 12

2 Answers2

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.

hardillb
  • 12,813
  • 1
  • 21
  • 34
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(&quot;Server Connection Established&quot;)
    else:
        print(&quot;bad connection Returned code=&quot;, rc)
    self.client.subscribe(self.sub_topic)

def on_subscribe(self, client, userdata, mid, granted_qos):
    print(&quot;Subscription complete&quot;)

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

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

def end(self):
    time.sleep(1)
    print(&quot;Ending Connection&quot;)
    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...

drascom
  • 11
  • 2