Retained message with msg.payload returns Function tried to send a message of type string

#1

I have a dashboard button node in which it is connected to a function node and defined the context.global.stat to retain the state of the button across function node, also have another mqtt in node to gather sensor data from it, both nodes, the (button --> function) and the (mqtt in) nodes are connected to a third function node, that I have defined the below code:

if( context.global.stat =="on")
{
    return[msg.payload,null];
}

if (context.global.stat == "off")
{
    return[null, null]; 
}

What I am after is to return only the values from mqtt in node if the button in the dashboard is "on", so when I run the above it returns the error below when the button is "on":

"Function tried to send a message of type string"

If I replace the return[msg.payload,null]; to return[msg,null]; it first return the msg of the button node then works normally and can read the sensor data from the mqtt in, so what I would like to have only the msg.payload returned for the mqtt in when the button is on.

The function node connected to the button node contains:

context.global.stat = msg.payload;
return msg;

image

0 Likes

#2

As the error says, you are trying to return a string. You must always return an object. I think you probably mean
return [msg, null];

0 Likes

#3

@MANNAS3 I expect that @Colin's suggestion will eliminate the error message. You might be able to use the gate node (node-red-contrib-simple-gate) instead of building from scratch.

0 Likes

#5

you are correct, and thank you for the guidance, I have used the msg before but was under the impression that I can return msg.payload in case I need to have the value, instead I have defined a new newmsg object to return msg.payload.

Regarding the on status that was returned with the msg, it seems was actually reflected due to the fact that I had another function node in which I have returned msg instead of null, so I had to replace with the below:

context.global.stat = msg.payload;
return null;

Thank you so much for your help with this!

0 Likes

#6

Thank you for the suggestion and will have a look into it :slight_smile:

0 Likes

#7

There should be no need to make a new message, just set msg.payload to what you want and then return msg. That is the normal convention as it means any other attributes are passed through unaffected, which can be useful.

1 Like