Hi all,
I’m new to Node-RED and I don’t know which is the best way to generate an alert or publish a message due to a variation in some values published on a topic.
I will explain my idea, I have a device sending the tank level value to a topic.
want generate an alert if three consecutive lectures the level is decreasing in some value, to notify me that probably I left some pipe open.
I don’t know if the best option is to generate two flows each time I receive a value, one storing the value to a DB an other one that retrieves some number of values and evaluates its
Thanks!
Hello Marc, it’s definitely possible to do it, but it might be a bit “difficult” if you’re not familiar with JavaScript.
Basically, if you have a similar setup like mine:
- Inject node (sending number 1)
- Chart node
- Debugging node (to ouput msg.payload in the Debug window)
After deploying your changes, press the inject node 3 times (for example).
Every time you press the Inject node, the msg.payload changes and it’s printed in the Debug window.
If you open the msg.payload > Array[1] > data > array[3], you’ll see that your latest value in the chart is added to the last position in the array (as you can see highlighted in yellow all the 1s in the screenshot above).
You could attach a Function node to the Chart node and write some JavaScript code that analyses the latest three readings in your chart (that are stored in the msg.payload) and trigger something.
I hope that helps!
Hi all,
It works 🙂 I followed more or less what are you saying Rui and I created a function block with this code
const THRESHOLD = 20; //Get the lenght of the msg var length = msg.payload[0].data[0].length; //Get the two last values var currentValue = msg.payload[0].data[0][length-1].y; var lastValue = msg.payload[0].data[0][length-2].y; if ((lastValue - currentValue) > THRESHOLD ) { var newMsg = { payload: "Alert message" }; } else { var newMsg = null; } return newMsg;
But I have some question about the node-red workflow. When the msg is initialized?
will the msg increase it size each time a message is received? What happens when I make the first evaluation with only one data element?
Thanks
- The msg is initialized after inserting the first value in your Chart node
- Every time you inject a new value in your Chart, it triggers the Chart output (which means your function node receives the msg.payload every time a new value is inserted)
- If you just have one data value in your array, you could create an if statement that checks if the array is empty or not
if(isEmpty(msg.payload[0].data[0][length-1].y)) {
// Object is empty (Would return true in this example) var currentValue = msg.payload[0].data[0][length-1].y;
} else {
var currentValue = 0;
}
Tip: Inputting a msg.payload containing a blank array [] will clear the Chart node.