Calculate realtime kWh (units of electricity consumption) from Power (W) sensor

I have added a sensor in HA which gives me current power usage (W) of my appliance.

I would like to create a sensor that shows the realtime Units consumed.

From what it seems like this should be the calculation ( I am ok with per minute calculation rather than per second calculation if that decreases CPU load)
KWh = Power in W * time in minutes / (1000 * 60)

So basically I want to create a sensor that multiplies the current numerical state of the Power sensor (in W) with the time in minutes the Power has been in the current numerical state. Then dividing by (1000 * 60) is easy

Thanks in anticipation

2 Likes

statistics sensor and template sensor

so if your current sensor was named sensor.power

sensor:
  - platform: statistics
    name: power_per_minute
    entity_id: sensor.power
    sample_size: 60 # This is assuming you are getting 1 sample a second.  Adjust otherwise.    

  - platform: template
    sensors:
      realtime_power:
        friendly_name: Realtime Power
        value_template: "{{ state_attr('sensor.power_per_minute', 'total') / (1000 * 60) }}"
        unit_of_measure: kwH 

You’ll have to adjust the sample size so that it properly takes a summation of power over the correct time to match a wM (watt minute).

Either way, you can adjust the equation and the sample size to get your desired information.

1 Like

There are two components with open pull requests that seem to meet your need. Hopefully they are accepted and merged… eventually.

https://github.com/home-assistant/home-assistant/pull/19703 -
Sometimes a device only provides power information (measured in W or kW).
This sensor does an integration of Power and time in order to measure energy consumed in kWh (standard energy measurement unit)

and

https://github.com/home-assistant/home-assistant/pull/19718 -
A utility meter sensor provides functionality to track consumptions of various utilities (e.g. energy, gaz, water, heating). From a User perspective utility meters operate in cycles (usually monthly) for billing purposes, this sensor will automatically reset the counter based on the configured cycle. On a reset an attribute will store the previous counter, providing the means for comparison operations (“did I spend more or less this month?”)

If you are feeling adventurous, you could pull the code from either (or both) of these and use them as custom components probably; until they get merged.

3 Likes

Both are coming in 0.87 :slight_smile:

  • sensor.integration (to help you convert Watt to KiloWattsHour)
  • utility_meter to track your energy consumptions
7 Likes

I tried both the Utility_Meter and the Integration Sensor components but neither are solutions.

The Utility_Meter adds up energy “pulses”. I uses energy sensors as input, not real time power as is stated in this posting.

The Integration Sensor does not have a reset service to reset the integration value after an hour.
I have requested this feature is this posting.

My power sensor changes when the power changes but not periodic so the Statistics Sensor won’t work either. The Integration Sensor would be ideal if it only had a reset.

You are missing the right workflow…

You use the integration sensor to get energy reading from your power sensor.

Then you use your utility_meter with the integration sensor as the source.

2 Likes

This looks like what im looking for to get the utility meter working…

Could you elaborate a little for us?

Do I need to convert my kWH sensor into a different format before putting that data into the utility meter component to get a correct reading?

Any help appreciated!

WD

If you already have a sensor providing kWh you use it directly in utility_meter in the source field.

I’m back to explain why the Integration Sensor to Utility_Meter flow has issues.
I created a test power waveform and fed that to the Integration Sensor to Utility_Meter flow
and my own python script.
My power waveform was simple so that I could do my own integration calculation
for the known good result.

minute/power
0 / 0
20 / 10
30 / 30
40 / 5
50 / 0

I hope you agree the known good result is 7.5 kWh

Here are the test results:
Integration Sensor to Utility_Meter flow: 8.463 kWh, error = 12.8%
Custom Python Script: 7.5113 kWh, error = 0.15%

Clearly, there are issues with the Integration Sensor to Utility_Meter flow.

  1. The integration sensor output never resets. This does not seem to bother the Utility_Meter
    but I wonder if there is a floating point overflow or loss of accuracy when subtracting large floating point numbers.
  2. The hourly sensor output from the Utility_Meter changes throughout the hour. You would expect it to change on the hour. It resets to zero on the hour so you would need a automation to sample the hourly sensor output one second before each new hour.
  3. Now here is the big reason why I don’t like the Integration Sensor to Utility_Meter flow.
    The Integration Sensor uses Trapezoidal rule for integration! While this is OK for continuously variable power sources it adds energy that does not exist for pulsating or staircase power waveforms.
    This is why the above testcase error is plus 12.8% It is adding triangles of energy between the staircase power levels.
    My power source is my gas furnace which ramps up the burners in three discrete steps until the temperature set point is satisfied. Another example could be a baseboard heater which pulses ON and OFF.

For those who want a more accurate flow, I provide this link to my python script. The installation instructions are provided in the file header. Feedback Welcome.

2 Likes

I don’t agree it’s 7.5 kWh… by my calculation it’s 8.33 kWh (It’s only 7.5 if you apply the “Left Riemann Sum” method)

You are applying the “Left Riemann Sum” method while the integration sensor is applying the “Trapezoidal Riemann Sum”. As you pointed out in your point 3!

We can discuss on the virtues of both methods, but HA documentation clearly states what the integration sensor is about, which method it uses. You have a good explanation in wikipedia https://en.wikipedia.org/wiki/Riemann_sum of the various methods and since this is a GENERIC integration sensor, it makes much more sense to use the Trapezoidal method.

Going back to your points

  1. Utility_meter will sum the variances of the source sensor, so it is not much bothered if a reset occurs (it will discard negative variances, that occur when a reset happens). In what respects to floating point overflow, it is using python Decimal class to avoid those issues, but there are always rouding errors.

  2. You have an attribute in the utility_meter sensor last_period so you don’t need any automation. Furthermore it continuously updates providing up to date consumption values (based on the variances of the source sensor)

  3. The integration sensor can always be improved with a configuration option to indicate which method to use (Left, Right, Middle, Trapezoidal)

3 Likes

The ‘real world’ correct answer is the “Left Riemann Sum” of 7.5 kWh for my type of power source so I will continue to use my custom python script. I will put in a feature request to add the “Left Riemann Sum” to the integration sensor.

On point 2.
Unfortunately, the last_period utility_meter sensor attribute is not documented. I don’t believe you can graph an attribute so you would have to add a template sensor to extract the attribute for graphing.

Here is an example template sensor used to graph energy use with an update only every hour.
“sensor.furnace_hourly” is from the utility_meter component.

  - platform: template
    sensors:
      util_meter:
        friendly_name: 'Hourly Utility Meter'
        unit_of_measurement: 'kWh'
        value_template: '{{ states.sensor.furnace_hourly.attributes.last_period | float }}'```
1 Like

There is a testcase for which the Integration Sensor to Utility_Meter flow that will produce an incorrect result even if the Integration Sensor uses the “Left Riemann Sum” method.

Consider this power waveform with a period of 2 hours:
minute/power
0 / 0
30 / 1
90 / 0
Basically, a square wave crossing the hour boundary.

The correct result should be 0.5 kWh every hour period.
I suspect that the improved Integration Sensor to Utility_Meter flow would produce an
alternating sequence of 0 kWh then 1.0 kWh which is not, strictly correct.

Maybe a better thing to do would to request a power input option to the Utility Meter component which considers time boundaries. My python script works for this testcase.

Again… this is not the way the integration sensor works, or is supposed to!

The integration sensor doesn’t care what happens at 60 min, because nothin happened at that time. All calculations will occur at the time the sensor changes (30 and 90). It will account correctly 1kWh.
There is no 0.5kWh at 60min because at that time there is nothing happening! Integration is done from state_change to state_change, there is no clock involved.

3 Likes

@dgomes: I think I can use your help…

I’m currently measuring pulses each time a watt is used. Using a counter, each time a pulse is send, I add one to the counter.

Am I correct to assume that I can use the value of the counter (which I think is in fact the total amount of kWh since I started counting) to the utility meter? Or do I make false assumptions?

Thanks in advance,
Ronald

You must first make sure what a pulse means… It is probably a kWh (or a fraction of a kWh)

If in fact it is a kWh you can use the utility_meter with source = your counter

1 Like

@dgomes I am doing exactly what you suggest.

@rdehuyss I am also reading pulses (in my case light blinks from energy meter from provider).
1 blink is 1/6400kWh (as stated on meter case)
I am using photodiode and ESP8266. Calculation from pulses to kWh is done on ESP - number of pulses * (1/6400).
Via MQTT sesnor I am getting value in kWh which is passed to utility meter.
I think you can also do this calculation on HA side via templating

In different solution (Sonoff POW R2) I don’t know what is pulse to kWh ratio but I have power in W (watts).
So I am using Integration Sesnor to get total power usage in kWh - same unit as my proviser chares me :slight_smile:

1 Like

Hi Diogo, I am using the integration sensor but I am having some issues with it sometimes showing NaN, I have triple checked that when I am summing all the sensor data containing my watt readings and they are numbers, as in they are displaying numbers. Any idea on what I can check to sort this out.

For Utility Meter, this is a great tool works perfect for my monthly readings, I would like to do Yesterday, is there a way this can be added?
Thanks
Dave

Hi Dave,

  1. Some sources don’t provide “proper numbers”, they just provide a string which happens to contain a number… One way to fix that is to use an intermediate sensor template that casts the “string value” into an actual number.

  2. Each utility_meter sensor has an extra attribute called last_period, so if your meter_period is daily then last_period will be “yesterday”. You can use a sensor template to pull the attribute into the frontend directly.

Thanks for responding, much appreciated. I will try the last period now. Thanks for that!
For casting a string I thought I am already doing that. See my code below.

  • platform: template
    sensors:
    total_ac_watts:
    value_template: “{{ (states(‘sensor.energy_ct1_watts’) | float) + (states(‘sensor.energy_ct4_watts’) | float) + (states(‘sensor.energy_ct_8_watts’) | float) + (states(‘sensor.energy_ct_10_watts’) | float) + (states(‘sensor.energy_ct_7_watts’) | float) + (states(‘sensor.energy_master_ac_ct5_watts’) | float) }}”
    friendly_name: ‘Total AC Power Use’
    unit_of_measurement: ‘W’
  • platform: integration
    source: sensor.total_ac_watts
    name: Total AC KWH
    unit_prefix: k
    round: 2
    This is one that is returning NaN.
    Thanks! Dave