Split mqtt message

902 views
Skip to first unread message

Lucian C. Vlaicu

unread,
Oct 25, 2017, 9:28:38 AM10/25/17
to Node-RED
Hi all,

I am a very beginner of using node-red and after play a little bit and, of course get into some issues:

Premises:

I am reading an mqtt topic where i get messages like : "stdout 1|0|0|0|0|0|0|0|125|0|1|1|28.33| 29.55 " , where stdout is the name of the topic.
These values are sensor values sent by an arduino over network (not sure how relevant it is).

Question:

How can i get split by "|" this message into different variables like first number 1 to put it on a gauge, second to text message, third into a progress bar for example...and so on.

Thanks in advance 

steve rickus

unread,
Oct 25, 2017, 10:16:31 AM10/25/17
to Node-RED
You can use the javascript split() function to break that string up into an array of strings, like so:
var parts = msg.payload.trim().split(/[ |]+/);

which returns this array
[ 'stdout',
 
'1',
 
'0',
 
'0',
 
'0',
 
'0',
 
'0',
 
'0',
 
'0',
 
'125',
 
'0',
 
'1',
 
'1',
 
'28.33',
 
'29.55']

At this point you can either create one msg object that contains all of these values in named "properties" (better for self-documentation, but you have to know what each position in the array means):
var readings = {
    topic
: parts[0],
    light1
: +parts[1],
    light2
: +parts[2],
etc
...
};
msg
.payload = readings;
return msg;

or you can define your function node to have 14 separate output ports, return an array of 14 new msg objects, and wire any or all of the array element to its own downstream flow:
var messages = parts.map(function(p) {return { payload: isNaN(p) ? p : +p }});
return messages;

In case you don't already have a good javascript reference, I recommend using the W3Schools site for looking up javascript functions for handling string/arrays/objects.
--
Steve

Lucian C. Vlaicu

unread,
Oct 26, 2017, 1:37:58 AM10/26/17
to Node-RED
Thanks a lot for your explanation

Cheers
Reply all
Reply to author
Forward
0 new messages