Margus
Margus

Reputation: 83

sum mqtt values with node-red

from MQTT feed I got thous values:

06/08/2018, 01:59:06View all 'emon/#' MQTT traffic
emon/emontx3/power1 : msg.payload : string [3]
588

emon/emontx3/power2 : msg.payload : string [3]
354

emon/emontx3/power3 : msg.payload : string [3]
740

how I can write function or use another node-red node to sum thous values to one ( 588+354+740=1682 )

Upvotes: 1

Views: 2299

Answers (2)

Michael
Michael

Reputation: 9042

Are the 3 messages reliably sent at about the same time with a decent gap between groups of messages? If so, you could just use a join node to combine the three messages into one. Then a subsequent change node or function node could add the values (see below). If not, you could store the values in flow variables until they're needed. However, you would need to know the conditions on which to add them.

enter image description here

Upvotes: 0

JanVdA
JanVdA

Reputation: 342

Instead of getting the 3 power values of the emonTx node being sent as 3 separate MQTT messages, it would be better to get it sent as a single MQTT message.

Eg in my setup, I got managed to get it sent as:

{"topic":"emonhub/rx/10/values","payload":"180,-209,37,1,261","qos":0,"retain":false,"_msgid":"a142b96c.e678d8"}

FYI I have used the following code in my node-red function node to parse the above MQTT message:

var parts        = msg.payload.split(",");
var CT1_power    = parseFloat(parts[0]);
var CT2_power    = parseFloat(parts[1]);
var CT3_power    = parseFloat(parts[2]);
var solar_power  = parseFloat(parts[3]);
var voltage      = parseFloat(parts[4]);
var phase1_power = CT1_power + solar_power;
var phase2_power = - CT2_power;
var phase3_power = CT3_power;
var total_power  = phase1_power + phase2_power + phase3_power;
msg.payload = { "total_power"  : total_power,
                "solar_power"  : solar_power,
                "voltage"      : voltage,
                "phase1_power" : phase1_power,
                "phase2_power" : phase2_power,
                "phase3_power" : phase3_power,
                "CT1_power"    : CT1_power,
                "CT2_power"    : CT2_power,
                "CT3_power"    : CT3_power,
};
return msg;

In my case "total_power" in the output msg.payload is the sum of the power used by the 3 phases measured by the emonTx node.

Upvotes: 0

Related Questions