Search code examples
ibm-cloudnode-red

How to add certain time intervals for the modules in node red?


I'm new to both STACKOVERFLOW and Node-RED and I have created a project of incubator in Node-Red on Bluemix Plaform.

It basically gets data through MQTT from arduino , and function node compares the received Temperature and humidity values with threshold. Based on this computed data, the action commands are sent back to arduino using MQTT again.

Here is the basic flow of the project

Project Flow

In the project I have also added some dashboard nodes for analytic.

The main question is how can I add stages to this project. Stages in the sense different time intervals.

1st stage : The threshold values for comparison should be 'XX' for initial 3 days.

2nd Stage : The threshold values for comparison should be 'YY' for next 7 days.

3rd Stage : The threshold values for comparison should be 'ZZ' for next 9 days.

4th Stage : The threshold values for comparison should be 'NN' for next 5 days.

I have total 4 stages in the project.

Intially, the threshold values should be X, and after 3 days, the threshold values must be changed. This process has to takes place thrice as I have 4 Time interval(4 stages).

How can I achieve this using shown Project flow..

In arduino I used to use millis() function for this purpose. But I did not find any option in Node-RED.


Solution

  • I would use a global variable to store the day from which you need to start and then have a case or If/Else logic to evaluate it and establish what stage you are now in. See: http://nodered.org/docs/writing-functions.html#storing-data

    That will be kept as long as your NodeRed instance is running. If you restart NodeRed, you will have to reset it. And you will need some logic to understand when you should set it back to some base value.

    EDIT the sample code below is to show how you could use the global.get/set. If this is for business purposes I'd be more careful and considered with the date processing than I am here!

    //Get current time and time started. Initialize if doesn't exist
    timestp = Date.now();
    if (!global.get('dateStarted')){
     global.set('dateStarted', timestp);
    }
    
    var dateStarted = global.get('dateStarted');
    
    //Check what stage
    if (dateStarted == timestp){
        node.warn("I'm new" +timestp);
    }
    // A day holds 86,400,000 milliseconds.  This needs more verification!!
    else if (dateStarted > (timestp + (86400000 * 3 ))){
        node.warn("3 days or more" +dateStarted);
    }