Get specific data from mqtt message

#1

Im struggling a bit with the piece of code below. The var msg1 and msg2 part is what i´ve added but it´s not working atm

What I want to achieve is when a MQTT message/object conains a topic with PM10 or PM2.5 then retrieve the payload and create a new payload msg. See the screenshot below for the data which Im retrieving in Node-RED.

is there a way to say if topic contains pm10 then retrieve payload?

var msg1 = msg.topic.PM10
var msg2 = msg.topic.PM25

var str = "Hello world, welcome to the universe.";
var n = str.includes("world");

msg.headers = {
    "X-Pin": "1",
    "X-Sensor": "TTNHennef-" + parseInt(msg["hardware_serial"], 16)
};
msg.payload = {
    "software_version": "TTNHennef-v1",
    "sensordatavalues": [
        {"value_type": "P1", "value": msg2},
        {"value_type": "P2", "value": msg1}
    ]
};
return msg;

Screenshot_4

0 Likes

#2

Hi @steffok,

The msg.topic property is a JavaScript String - there are a variety of ways in JavaScript to test if one String contains another. For example:

// Using a Regular Expression:
if (/PM10/.test(msg.topic)) {
   // This is a message on a topic with PM10 in it
   // msg.payload will contain the corresponding value
}

// Alternatively, using String.indexOf
if (msg.topic.indexOf("PM10") > -1) {
   ....
}

But, having explained that, your function suggests you want to be able to send on a single message that contains both values in one go - is that the case?
You have two separate messages arriving from the MQTT node - one with a topic ending in PM2.5 and one ending with PM10 - they are separate calls of the Function node. If you want to combine them then there are some other approaches needed. For example, a Join node configured to combine the two messages into one - which you can then pass to a Function node to generate the result you want. If this is the sort of thing you want to do, let us know and we can help with more of the finer detail on joining messages.

0 Likes

#3

thanks for guiding me into the right direction. Will give it a try tomorrow.
Regarding the data - I want to sent the data to the lufdaten api and so far I can see I can send both with http post. But Im not a diehard programmer :slight_smile: just trying and see where Im heading to

0 Likes