Calculate current consumption based on total power consumption

Hi,

need some help, please.
Got an sensor which receives the total power consumed. Updated twice per minute based on my power meter. Values are stored in postgres db.

I want to calculate the difference between the current value and the previous value to calculate the real time consumption (with some delay).

Br,

If you are using nodered, it would be very easy to create a flow in it with a sensor at the end to store the real-time consumption.

Using Node Red, my function to calculate average power usage (W) between 2 updates of the global consumption meter (in Wh) :

var Timestamp = Number(msg.payload);
var Prev_Timestamp = flow.get("Prev_Timestamp" );
var Index = flow.get("Index" );
var Prev_Index = flow.get("Prev_Index" );
var Puissance;
 
if (isNaN(Prev_Index))
{
    flow.set("Prev_Index", Index);
    flow.set("Prev_Timestamp", Timestamp);  
}
else if ((Timestamp-Prev_Timestamp > 19000) && (Index > Prev_Index))
{
    Puissance = Math.floor((Index-Prev_Index)/(Timestamp-Prev_Timestamp)*1000*3600);
     
    flow.set("Prev_Index", Index);
    flow.set("Prev_Timestamp", Timestamp);
     
    if (Puissance < 10000)
    {
        msg.topic = "Puissance";
        msg.payload = Puissance;
        return msg;
    }
}

Power is calculted in Watt
Timestamps in NodeRed are in milliseconds
I limit the update of the sensor to once per 20 seconds
I also applied a quick filter to avoid crazy numbers when restarted my global consumption meter sensor.

nice, unfortunately i dont run node red, any idea how to do this via template engine directly in HA?

Use the same function in a core HA automotion.

1 Like

can you help me, please

Sorry, I’ve never used HA native automations, I’ve always found Node Red easier to use and understand, but a lot of progress have been made on HA native automations these last months.

HI, can you provide the whole flow?

Sure, that’s really short and simple :

[{"id":"53a567e0.517d58","type":"tab","label":"Flow 1","disabled":false,"info":""},{"id":"c7c94832.64f0c8","type":"change","z":"53a567e0.517d58","name":"TimeStamp","rules":[{"t":"set","p":"payload","pt":"msg","to":"","tot":"date"}],"action":"","property":"","from":"","to":"","reg":false,"x":478,"y":85,"wires":[["cd35b838.9e87e8"]]},{"id":"9de6ba13.77d938","type":"api-call-service","z":"53a567e0.517d58","name":"Update Puissance","server":"ec30a50e.1b4f88","version":3,"debugenabled":false,"service_domain":"var","service":"set","entityId":"var.puissance","data":"{\"value\" : msg.payload}","dataType":"jsonata","mergecontext":"","mustacheAltTags":false,"x":1110,"y":85,"wires":[[]]},{"id":"3d9c8ed0.290722","type":"server-state-changed","z":"53a567e0.517d58","name":"Teleinfo Index","server":"ec30a50e.1b4f88","version":3,"exposeToHomeAssistant":false,"haConfig":[{"property":"name","value":""},{"property":"icon","value":""}],"entityidfilter":"sensor.teleinfo_index","entityidfiltertype":"exact","outputinitially":true,"state_type":"str","haltifstate":"","halt_if_type":"num","halt_if_compare":"is","outputs":1,"output_only_on_state_change":false,"for":"","forType":"num","forUnits":"minutes","ignorePrevStateNull":false,"ignorePrevStateUnknown":false,"ignorePrevStateUnavailable":false,"ignoreCurrentStateUnknown":false,"ignoreCurrentStateUnavailable":false,"outputProperties":[{"property":"payload","propertyType":"msg","value":"","valueType":"entityState"}],"x":87,"y":51,"wires":[["ec9c8099.e12c6"]]},{"id":"ec9c8099.e12c6","type":"delay","z":"53a567e0.517d58","name":"","pauseType":"rate","timeout":"5","timeoutUnits":"seconds","rate":"1","nbRateUnits":"30","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":true,"x":284,"y":51,"wires":[["c7c94832.64f0c8","70a41cba.733214"]]},{"id":"cd35b838.9e87e8","type":"delay","z":"53a567e0.517d58","name":"","pauseType":"delay","timeout":"5","timeoutUnits":"milliseconds","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"x":665,"y":85,"wires":[["c1fbf1d8.441ec"]]},{"id":"c1fbf1d8.441ec","type":"function","z":"53a567e0.517d58","name":"Calcul de Puissance","func":"var Timestamp = Number(msg.payload);\nvar Index = flow.get(\"Index\",\"file\");\nvar Prev_Index = flow.get(\"Prev_Index\",\"file\");\nvar Prev_Timestamp = flow.get(\"Prev_Timestamp\",\"file\");\nvar Prev_Puissance = flow.get(\"Prev_Puissance\",\"file\");\nvar Puissance;\n\n // Get a pretty date in the format: `Mar 20, 13:04`\nvar date = new Date().toLocaleDateString('fr-FR', {\n    month: 'short',\n    day: 'numeric',\n    hour12: false,\n    hour: 'numeric',\n    minute: 'numeric'\n})\nvar statusText;\n\nif (isNaN(Prev_Index))\n{\n    flow.set(\"Prev_Index\", Index, \"file\");\n    flow.set(\"Prev_Timestamp\", Timestamp, \"file\"); \n}\nelse if ((Timestamp-Prev_Timestamp > 29000) && (Index > Prev_Index))\n{\n    Puissance = Math.floor((Index-Prev_Index)/(Timestamp-Prev_Timestamp)*1000*3600);\n    \n    if (Puissance < 1000)\n    {\n        Puissance = Math.round(Puissance/10)*10;\n    }\n    else\n    {\n        Puissance = Math.round(Puissance/50)*50;\n    }\n    \n    flow.set(\"Prev_Index\", Index, \"file\");\n    flow.set(\"Prev_Timestamp\", Timestamp, \"file\");\n    \n    if (Puissance!=Prev_Puissance && Puissance < 10000)\n    {\n\n        statusText = Puissance + ` at: ${date}`\n        node.status({fill: \"green\", shape: \"dot\", text: statusText});\n\n        flow.set(\"Prev_Puissance\", Puissance, \"file\");\n        msg.topic = \"Puissance\";\n        msg.payload = Puissance;\n        return msg;\n    }\n}","outputs":1,"noerr":0,"initialize":"","finalize":"","x":882,"y":85,"wires":[["9de6ba13.77d938"]]},{"id":"70a41cba.733214","type":"change","z":"53a567e0.517d58","name":"Index Teleinfo","rules":[{"t":"set","p":"#:(file)::Index","pt":"flow","to":"payload","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":488,"y":34,"wires":[[]]},{"id":"ec30a50e.1b4f88","type":"server","name":"Home Assistant","version":1,"legacy":false,"addon":true,"rejectUnauthorizedCerts":true,"ha_boolean":"y|yes|true|on|home|open","connectionDelay":true,"cacheJson":true}]

As an HA trigger-based template sensor, measuring average power in watts based off an energy meter incrementing in watt-hours:

template:
  - trigger:
      - platform: state
        entity_id: sensor.energy_meter_wh
    sensor:
      - name: Average power
        unit_of_measurement: 'W'
        state: >-
          {% set old_ts = trigger.from_state.last_updated|as_timestamp %}
          {% set new_ts = trigger.to_state.last_updated|as_timestamp %}
          {% set delta_ts = new_ts - old_ts %}
          {% set old_wh = trigger.from_state.state|float %}
          {% set new_wh = trigger.to_state.state|float %}
          {% set delta_wh = new_wh - old_wh %}
          {{ delta_wh * 3600 / delta_ts }}

If you actually wanted a current sensor measuring in amps, use:

          {{ (delta_wh * 3600 / delta_ts) / YOUR_VOLTAGE }}

and change the name & unit_of_measurement accordingly. All untested, but ought to work.

2 Likes

I’m getting an error.
My total meter entity_id is “sensor.current_consumption”, on this sensor I get updates every 30 seconds with the total meter value.

can you help me?

You cannot put this in the template editor, as it uses the trigger data from the automation.

You will have to put it in an automation and reload automations to see it (hopefully) working.

Just replace my sensor.energy_meter_wh with your sensor.current_consumption and adjust units as needed. What units does that sensor report?

Possibly some confusion from “current” meaning both “at this moment” and “electrical flow in Amps”.