Code question from a dopey newbe[solved]

#1

Hello,
I am setting up a flow for automating my greenhouse using a pi 3.
I have some prior experience coding in Qt c++ but it has been a few years...
I want to return 'true' or 'false' to operate a switch but due to my lack of coding skills 'result' ends up 'undefined' and msg.payload returns 'undefined'.
I hope someone can set me straight here on setting the variables in functions...
Best regards,
Jon

    //gets the temp and humidity reading from the DHT11
var hum = msg.humidity;
var tmp = msg.payload;
var result;
setInterval(function(){
    var hour = new Date().getHours();
    if (hour >= 8 && hour < 18) {
        controlMister(); 
    }
} , 1000*60);
function controlMister(){
if(hum < 60 && tmp > 10)
{
    result = "false";
}
    else
{
        result = "true";
}
//node.warn(result);
}
node.warn(result);
msg.payload = result;
return msg;
0 Likes

#2

How do you use code tags on this forum?
Jon

0 Likes

#3
0 Likes

#4

Thank you!
Cheers,
Jon

0 Likes

#5

Try:

//gets the temp and humidity reading from the DHT11
var hum = msg.humidity;
var tmp = msg.payload;
var result;

setInterval(function(){
    var hour = new Date().getHours();
    if (hour >= 8 && hour < 18) {
        controlMister();
    }
}, 1000*60);

function controlMister(){
    if(hum < 60 && tmp > 10) {
        result = "false";
    } else {
        result = "true";
    }
    //node.warn(result);
    msg.payload=result;
    node.send(msg);
}
//node.warn(result);
//msg.payload = result;
return null;

to test it now you should change this line

    if (hour >= 8 && hour < 20) {
0 Likes

#6

Thank you!
Works as intended!
Cheers,
Jon

0 Likes

#7

Why is 'result' (which I assumed was a global since I added it outside the function) data not maintained/exposed outside of the function?

0 Likes

#8

result is a node local var, if you need a global, you have to use global.get() and global.set().

https://nodered.org/docs/writing-functions#storing-data

... and in your case here when leaving the function node, result isn't set.

0 Likes

#9

AHA!
Thank you very much.
Cheers,
Jon

0 Likes