Function node help. Want to compare 2 values and average out 2 values

[{"id":"d04e4f6f0c28aa37","type":"tab","label":"Flow 1","disabled":false,"info":"","env":[]},{"id":"31bf457ce7770cb4","type":"api-current-state","z":"d04e4f6f0c28aa37","name":"Garage temp1","server":"ab3e2c53.e3491","version":3,"outputs":1,"halt_if":"","halt_if_type":"str","halt_if_compare":"is","entity_id":"sensor.temperature_garage","state_type":"str","blockInputOverrides":false,"outputProperties":[{"property":"payload","propertyType":"msg","value":"","valueType":"entityState"},{"property":"data","propertyType":"msg","value":"","valueType":"entity"}],"for":"0","forType":"num","forUnits":"minutes","override_topic":false,"state_location":"payload","override_payload":"msg","entity_location":"data","override_data":"msg","x":380,"y":375,"wires":[[]]},{"id":"8f8ec292d5cb1e35","type":"api-current-state","z":"d04e4f6f0c28aa37","name":"Garage temp2","server":"ab3e2c53.e3491","version":3,"outputs":1,"halt_if":"","halt_if_type":"str","halt_if_compare":"is","entity_id":"sensor.temperature_garage_2","state_type":"str","blockInputOverrides":false,"outputProperties":[{"property":"payload","propertyType":"msg","value":"","valueType":"entityState"},{"property":"data","propertyType":"msg","value":"","valueType":"entity"}],"for":"0","forType":"num","forUnits":"minutes","override_topic":false,"state_location":"payload","override_payload":"msg","entity_location":"data","override_data":"msg","x":380,"y":435,"wires":[[]]},{"id":"f04687f13ea21b69","type":"inject","z":"d04e4f6f0c28aa37","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":195,"y":405,"wires":[["31bf457ce7770cb4","8f8ec292d5cb1e35"]]},{"id":"9974e0f5cdd0f7d0","type":"comment","z":"d04e4f6f0c28aa37","name":"I would like temp1 and temp2 to be compared, if they are more than 3 degrees different, alert me","info":"","x":465,"y":315,"wires":[]},{"id":"04ee3b3afb1cb6af","type":"api-call-service","z":"d04e4f6f0c28aa37","name":"Alert Jim.","server":"ab3e2c53.e3491","version":5,"debugenabled":false,"domain":"notify","service":"notify_jim","areaId":[],"deviceId":[],"entityId":[],"data":"{\"title\":\"Garage temp sensors do not agree\",\"message\":\"Garage temp sensors do not agree. Please check them.\",\"data\":{\"color\":\"red\",\"clickAction\":\"/lovelace/1\"}}","dataType":"json","mergeContext":"","mustacheAltTags":false,"outputProperties":[],"queue":"none","x":750,"y":405,"wires":[[]]},{"id":"d020b6e81c9c520f","type":"function","z":"d04e4f6f0c28aa37","name":"????","func":"\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":565,"y":405,"wires":[[]]},{"id":"f4359f7afee77083","type":"api-current-state","z":"d04e4f6f0c28aa37","name":"Garage temp1","server":"ab3e2c53.e3491","version":3,"outputs":1,"halt_if":"","halt_if_type":"str","halt_if_compare":"is","entity_id":"sensor.temperature_garage","state_type":"str","blockInputOverrides":false,"outputProperties":[{"property":"payload","propertyType":"msg","value":"","valueType":"entityState"},{"property":"data","propertyType":"msg","value":"","valueType":"entity"}],"for":"0","forType":"num","forUnits":"minutes","override_topic":false,"state_location":"payload","override_payload":"msg","entity_location":"data","override_data":"msg","x":370,"y":630,"wires":[[]]},{"id":"027b80529928f841","type":"api-current-state","z":"d04e4f6f0c28aa37","name":"Garage temp2","server":"ab3e2c53.e3491","version":3,"outputs":1,"halt_if":"","halt_if_type":"str","halt_if_compare":"is","entity_id":"sensor.temperature_garage_2","state_type":"str","blockInputOverrides":false,"outputProperties":[{"property":"payload","propertyType":"msg","value":"","valueType":"entityState"},{"property":"data","propertyType":"msg","value":"","valueType":"entity"}],"for":"0","forType":"num","forUnits":"minutes","override_topic":false,"state_location":"payload","override_payload":"msg","entity_location":"data","override_data":"msg","x":370,"y":690,"wires":[[]]},{"id":"68440bc92aeee2f9","type":"inject","z":"d04e4f6f0c28aa37","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":185,"y":660,"wires":[["f4359f7afee77083","027b80529928f841"]]},{"id":"47944d98fa6accaa","type":"comment","z":"d04e4f6f0c28aa37","name":"I would like temp1 and temp2 to be averaged and written to a global variable","info":"","x":395,"y":570,"wires":[]},{"id":"bd998ba21c3bc416","type":"function","z":"d04e4f6f0c28aa37","name":"????","func":"\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":555,"y":660,"wires":[[]]},{"id":"b887ee91d3659ffd","type":"change","z":"d04e4f6f0c28aa37","name":"Set msg.payload to global average_temp","rules":[{"t":"set","p":"payload","pt":"msg","to":"average_temp","tot":"global"}],"action":"","property":"","from":"","to":"","reg":false,"x":850,"y":660,"wires":[[]]},{"id":"ab3e2c53.e3491","type":"server","name":"AvilaSmartHome","version":5,"addon":true,"rejectUnauthorizedCerts":true,"ha_boolean":"y|yes|true|on|home|open","connectionDelay":true,"cacheJson":true,"heartbeat":false,"heartbeatInterval":30,"areaSelector":"friendlyName","deviceSelector":"friendlyName","entitySelector":"friendlyName","statusSeparator":"at: ","statusYear":"hidden","statusMonth":"short","statusDay":"numeric","statusHourCycle":"h23","statusTimeFormat":"h:m","enableGlobalContextStore":true}]

I have 2 temp sensors in garage. I would like them compared and if they differ more than 3 deg, to get an alert. I know I need a function node, just dont know what the heck to put in it.

image

Also with those same 2 sensors, I would like to average them out and write it to a variable.

var temp1 = msg.payload.state;
var temp2 = msg.data.state;

if (Math.abs(temp1 - temp2) > 3) {
    msg.payload = {
        title: "Garage temp sensors do not agree",
        message: "Garage temp sensors do not agree. Please check them.",
        data: {
            color: "red",
            clickAction: "/lovelace/1"
        }
    };
    return msg;
}

This is from chat ai

You gave me a chance to play

Full text

You can use a “function” node to compare the two temperature values and check if the difference is greater than 3 degrees. In the function node’s “func” field, you will need to write some JavaScript code to accomplish this. Here’s an example of what that code might look like:

Copy code

var temp1 = msg.payload.state;
var temp2 = msg.data.state;

if (Math.abs(temp1 - temp2) > 3) {
    msg.payload = {
        title: "Garage temp sensors do not agree",
        message: "Garage temp sensors do not agree. Please check them.",
        data: {
            color: "red",
            clickAction: "/lovelace/1"
        }
    };
    return msg;
}

This code uses the “Math.abs” function to calculate the absolute value of the difference between the two temperature values. If that difference is greater than 3, it sets the “msg.payload” property to a new object containing the alert information, and returns the modified message.

Then you can wire this function node to the “API Call Service” node, so that the service is called and the alert is sent.

Also with those same 2 sensors, I would like to average them out and write it to a variable.

You can use another function node to calculate the average of the two temperature values and write it to a variable. Here’s an example of what that code might look like:

Copy code

var temp1 = msg.payload.state;
var temp2 = msg.data.state;

// calculate average
var avg = (temp1 + temp2) / 2;

// create a new variable to hold the average
global.set("garage_temp_avg", avg);

return msg;

This code first gets the temperature values from the “msg.payload.state” and “msg.data.state” properties, then calculates the average by adding the two values and dividing by 2. Then it uses the “global.set()” function to create a new global variable named “garage_temp_avg” and sets its value to the calculated average.

You can wire this function node to the same function node or after the first function node that compare the temperature and check the difference. You can use the global variable “garage_temp_avg” to access the average temperature in other flows or use it to trigger some action.

You can not make it in the flow you have set up.
The reason is that you split your flow and that makes it two different flows, where on state node is first received and computed without the knowledge og the other and then vice-versa.
You can merge messages again, but it is error-prone.

You should drop the get state nodes and get the data directly from the Global Context Data that NodeRed keeps in sync with HA.

Here is an example on a function node that extracts a few sun values from the Global Context Data.

[{"id":"fcb8501ba4e0c02b","type":"function","z":"be03f9025a1f137a","name":"function 1","func":"msg.sun = global.get('homeassistant').homeAssistant.states[\"sun.sun\"];\nmsg.sun_state = global.get('homeassistant').homeAssistant.states[\"sun.sun\"].state;\nmsg.sun_attr_next_dawn = global.get('homeassistant').homeAssistant.states[\"sun.sun\"].attributes.next_dawn;\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":375,"y":75,"wires":[["36f148efe227cbac"]]}]

You can find other values by opening up the Context Data in the upper right icon menu and then refresh the Global section.

And then make a combination with the code iscraigh have proposed.

Mine just shows me some random item. How do I get to see other ones?

It shows the homeAssistant object.
Expand that.

@iscraigh @WallyR thank you for all the help. I got the compare flow working good. But I cant get the average flow working.

I tried using the state’s as they are checked, or using the global context data. Both end up with ‘NaN’.

In the change node, I am just chaning global.garage_temp_avg to msg.avg so I can visualize the result for now.

[{"id":"4c0e526340d14136","type":"tab","label":"Flow 2","disabled":false,"info":"","env":[]},{"id":"3c40ab700c82da8e","type":"debug","z":"4c0e526340d14136","name":"debug 7","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":1020,"y":165,"wires":[]},{"id":"b0fd264d687e7136","type":"change","z":"4c0e526340d14136","name":"","rules":[{"t":"set","p":"avg","pt":"msg","to":"garage_temp_avg","tot":"global"}],"action":"","property":"","from":"","to":"","reg":false,"x":865,"y":75,"wires":[["3c40ab700c82da8e"]]},{"id":"1e4559964f53b991","type":"api-current-state","z":"4c0e526340d14136","name":"Garage temp1","server":"ab3e2c53.e3491","version":3,"outputs":1,"halt_if":"","halt_if_type":"str","halt_if_compare":"is","entity_id":"sensor.temperature_garage","state_type":"str","blockInputOverrides":false,"outputProperties":[{"property":"temp1","propertyType":"msg","value":"","valueType":"entityState"}],"for":"0","forType":"num","forUnits":"minutes","override_topic":false,"state_location":"payload","override_payload":"msg","entity_location":"data","override_data":"msg","x":295,"y":75,"wires":[["caf4710351f8d93e"]]},{"id":"caf4710351f8d93e","type":"api-current-state","z":"4c0e526340d14136","name":"Garage temp2","server":"ab3e2c53.e3491","version":3,"outputs":1,"halt_if":"","halt_if_type":"str","halt_if_compare":"is","entity_id":"sensor.temperature_garage_2","state_type":"str","blockInputOverrides":false,"outputProperties":[{"property":"temp2","propertyType":"msg","value":"","valueType":"entityState"}],"for":"0","forType":"num","forUnits":"minutes","override_topic":false,"state_location":"payload","override_payload":"msg","entity_location":"data","override_data":"msg","x":500,"y":75,"wires":[["2958132e7045fcc2"]]},{"id":"2958132e7045fcc2","type":"function","z":"4c0e526340d14136","name":"function 6","func":"var temp1 = msg.temp1;\nvar temp2 = msg.temp2;\n\n// calculate average\nvar avg = (temp1 + temp2) / 2;\n\n// create a new variable to hold the average\nglobal.set(\"garage_temp_avg\", avg);\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":675,"y":75,"wires":[["b0fd264d687e7136"]]},{"id":"10bfa740766c6105","type":"inject","z":"4c0e526340d14136","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":105,"y":75,"wires":[["1e4559964f53b991"]]},{"id":"ad6821f06c78493c","type":"function","z":"4c0e526340d14136","name":"function 7","func":"var temp1 = global.get('homeassistant').homeAssistant.states[\"sensor.temperature_garage\"].state;\nvar temp2 = global.get('homeassistant').homeAssistant.states[\"sensor.temperature_garage_2\"].state;\n\n// calculate average\nvar avg = (temp1 + temp2) / 2;\n\n// create a new variable to hold the average\nglobal.set(\"garage_temp_avg\", avg);\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":285,"y":180,"wires":[["7dfd64732c931e8d"]]},{"id":"7fd803e962cf26e6","type":"inject","z":"4c0e526340d14136","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":105,"y":180,"wires":[["ad6821f06c78493c"]]},{"id":"7dfd64732c931e8d","type":"change","z":"4c0e526340d14136","name":"","rules":[{"t":"set","p":"avg","pt":"msg","to":"garage_temp_avg","tot":"global"}],"action":"","property":"","from":"","to":"","reg":false,"x":470,"y":180,"wires":[["3c40ab700c82da8e"]]},{"id":"ab3e2c53.e3491","type":"server","name":"AvilaSmartHome","version":5,"addon":true,"rejectUnauthorizedCerts":true,"ha_boolean":"y|yes|true|on|home|open","connectionDelay":true,"cacheJson":true,"heartbeat":false,"heartbeatInterval":30,"areaSelector":"friendlyName","deviceSelector":"friendlyName","entitySelector":"friendlyName","statusSeparator":"at: ","statusYear":"hidden","statusMonth":"short","statusDay":"numeric","statusHourCycle":"h23","statusTimeFormat":"h:m","enableGlobalContextStore":true}]

Function7 contains:

Garage temp1, temp2, and function6 contain:


image
image

Sometimes you see number values, bit they are in fact strings and there needs to be converted before being used as numbers.
I can’t here remember if it is toInt() or |int or some other function that does it. Maybe a Google search can help you.
Remember that it is JavaScript you are programming and if the numbers have decimals, then you might need float instead of int.

You can use node-red-contrib-boolean-logic-ultimate (node) - Node-RED

Comparator https://www.youtube.com/watch?v=fDRsQPu3bG4

Follower - I want to do exactly something like this with 2 sensors outside and inside a room in the house whether to turn on an air conditioner or a light