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

It was a dumb question, i was thinking in something else. Sorry

Unrelated to your question/problem:

donā€™t mistake power for energy

W is Power
Wh is Energy

1 Like

Good evening.

I just followed above tutorial and created my power per minute sensor

when I had sample size = 60 as in most first yaml example and went to check server before rebooting HA it wasnā€™t happy with it and giving me an error.

Then I just removed the line with sample size and no error was showing then. After reboot I received this sensor and in itā€™s body sampling size is now 20. Device is smart plug by Tyua with energy monitoring function built in. So should I now replace 60 by 20 in bottom line equation? to look like

ā€œ{{ state_attr(ā€˜sensor.power_per_minuteā€™, ā€˜totalā€™) / (1000 * 20) }}ā€

Thanks for possible help!

P.S. correction: my device instead of sample size called it sampling size what gave me an error and when I corrected it in configuration line HA got happy with it and after reboot started to show consumption in watts. Now instead of watching many small numbers (when in watts) I would prefer less numbers shown in kW, so I guess I should insert " * 0.001" in some line.

1 Like

How did you do the integration ?

I have a HACS installation and no access to the underlying sensor itself.

I guess the basic sensor has to run at 20 samples per minute and then this sensor can follow too but not vice versa.

I can add the parameter here in configuration.yaml but how can I check if HA is really getting 20 values per minute for each sensor ?

### POWER CONSUMPTION SENSORS  ###
 - platform: template  
    sensors:
      watt_1: 
        friendly_name:       'COUCH'
        unit_of_measurement: 'W'
        icon_template:       'mdi:router-wireless'
        value_template:      "{{ state_attr ('switch.couch', 'current_consumption') }}"
        sampling_size:       '20'

### ENERGY CONSUMPTION SENSORS ###
  - platform:      integration
    name:          'kwh'
    source:        'sensor.watt_couch'
    unit_prefix:   'k'
    round:         3
    method:        'left'
UPDATE + SOLUTION for issues described above:
=============================================

It does not work like described above cause the template plattform does not know a sample_size attribute nor a sample_sizing attribute.

You have to use the sample parameter at the root or source, the real sensor created in my case by the HARC integration outside [configuration.yaml]

Open the [customize.yaml] file and add the following for each sensor cause then the sampling_size attribute seems to work for tuya, maybe not the fastest, but I do not need 60 data a minute or 3600 per hour and 86.400 per day to track my watts or Wh.

switch.couch:
  sampling_size: '20'

And then you can check at least if the attribute has been created successfully in the developer tools pane - even though I do not know how to check if the samle size is working and if it is working right (except watching graphs for a 1 hour time frame).
These data should mean that we get 20 measurements per minute or 1200 in an hour.
But the graph of 1 hour is not showing if he is relying on 1200 datapoints or not except you can zoom a lot or reduce that frame in a special card to 1 minute instead of 60.
At least I did not get any errors anymore and the basic history graphs over 1 hour look smooth.
image

Iā€™m also stuck

I copy&pasted this two sensors to track the energy of some photovoltaik module

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

  - platform: template
    sensors:
      realtime_power_pv_anlage:
        friendly_name: Realtime Power Solaranlage
        value_template: "{{ state_attr('sensor.power_per_minute', 'total') / (1000 * 60) }}"
        unit_of_measurement: kWh

and my original sensor shows me following power over time:
grafik

and my new virtual energy sensor calculates following:
grafik
you see one weird thing
on the left side there is some degration on the energy
but within the original power sensor you see ther was power pumping in the system but while loosing the sun less and less and less
obviously the ENERGY sensor should integrate into PLUS not into MINUS i guess??

The change in the gradient on the right side was some mistake by me
I changed the sampling rate to the correct one (thanks @typxxi for your hint )

That is the big issue if the sample size does not lead to answers in time. I am not sure why this happens cause some report that the plug or sensor gets in an instable state torn between the cloud service and home assistant cause I have still both in place cause I wanted to be sure that HA is the more reliable solution. But that is still questionable cause from time to these things happen like your "explosion at 8 am in the morning as if someone hat turned it on.

In such case the socket will reply 20 times to HA and maybe 15 times to the cloud provider like tuya etc. and then the HA completely dies. You are using your socket only for a part time device and therefore you do not really know what has happened from about 18 to 08 but I have used it as watt meter in the big plug with a lot of devices just to monitor and there I have learned that this can cause 3 to 9 hour long breaks that you do not really recognice cause during night the W is 0 regardless if it works or not.

You might try to add a ā€œpresence checkerā€ that simply measures the voltage to compare that curren voltage with the previous measurement. If it is power connected the AC voltage will jump a tiny bit and that means the system is working even though watts are 0.

In a PV Anlage I suggest to go lower to 10 per minute cause every 6 seconds is quite good enough and within the timeframe of the mppt tracker that will search a new optimum in case clouds come by.
10 would make it more reliable.

One final observation: It felt for me that somehow my Pi Hole was involved to as a cause for issues.
Why? I had trouble recently and observed one morning that all my power sensors where not reporting and checked since when. Later I recogniced that my internet did not work anymore and that the pi-Hole had an issue, a long time issue , a corrupted database or so and in the logs I found the break down moment which was matching the time of 3 active sensors that also since then showed nothing.

Not sure, if that is really true, but after I had rebuild and set up a new pi-Hole database I found the Watt sensore working again.

I also guess you live close to mountains or your PV Anlage starts late and goes pretty early to bed or you have close neighbours on 2 sides with tall buidings. These graphs look like a PV in a heavily shadowed spot cause I have a friend in Bavaria who has similiar results / curves due to high mountains - or a PV in too deep valleys as he used to say.

I am know monitoring my pi-hole very carefully but as usual nothing is happening, all fine - due to the new DB that still works fine.

1 Like

I am using the Trapezoidal Riemann Sum integrating sensor. And when my energy meter was connected to small appliances (bulb 10W, cell phone charger etc), everything was more or less ok. Today I decided to check the use of the electric kettle. That is, the maximum power of 2kW in a short time. The application from the energy meter showed me that the kettle consumed 0.1kWh, while the HA consumption showed 10kWh. This is 100 times more. Anyone know what could be the reason for this?

You need to use the left method for energy spikes.

If you donā€™t use the ā€œleftā€ method, the following is happening:
if your kettle is off for 10 days and then goes to 2kW, HA is assuming that is going from 0 to 2kW over the period of 10 days.

Ok, thank you. I will try.

Thereā€™s another separate issue with the integration sensor. It only updates when the input sensor updates, which is not always sufficient.

For example: Iā€™m monitoring the energy used by our pool filtration system. Itā€™s power usage stays exactly the same throughout the day after a brief priming phase. In this scenario the integration sensor does not calculate the energy used until the end of the day when the pump stops. So not real time at all.

Iā€™ve create an issue in GitHub for this:

Hope I can borrow this thread and extend to my question and thus contribute to someone else who has the same issue.

I have aa heatpump that exposes sensor which measure realtime current in Amps and per phase. My final goal is to to be able to add consumption of heatpump. There is a Add Device function in the energy dashboard and I already have added many other devices. For that sensor to be added to the dashboard it needs to have

device_class: energy
unit_of_measurement: kWh #or Wh
state_class: total_increasing # or total

But I am not there yet.

I have come up with this conversion and sum from Amps to Watts for 3 all phases and then integration to energy and then utilising it daily. Does this look correct? Will this be possible to add as a device to energy dashboard?

template:
# This is Apparent power derived by multiplying voltage and current and for all 3 phases and in Watts. Will NOT be correct though for non-resistive loads like motors and heat pumps since you will need to multiply it by the power factor too which I dont have. Anyway Integration platform further down will convert it to kW                             
  - sensor:                                                                                                                                                                       
    - name: "Template Nibe 174067 Power Calculated"                                                                                                                               
      unique_id: template_nibe_174067_power_calculated                                                                                                                            
      state: "{{ (states('sensor.nibe_174067_40083')  |float * 230) + (states('sensor.nibe_174067_40081')  |float * 230) + (states('sensor.nibe_174067_40079')  |float * 230 ) }}"
      device_class: power                                                                                     
      icon: mdi:lightning-bolt                                                                                
      unit_of_measurement: "W"                                                                                

# Riemann sum integral to calculate consumed energy                                                                                                                               
sensor:                                                                                                                                                                           
  - platform: integration                                                                                                                                                         
    source: sensor.template_nibe_174067_power_calculated                                                                                                                          
    name: "Nibe heatpump total consumer energy"                                                                                                                                   
    method: left                                                                                                                                                                  
    unit_prefix: k                                                                                                                                                                
    unit_time: h                                                                                                                                                                  
    round: 2                                                                                                                                                                      

# Consumed energy                                                                                                                                                                 
utility_meter:
  utility_heatpump_hurly_consumed_energy:                                                                                                                                         
    source: sensor.nibe_174067_total_consumed_energy                                                                                                                              
    cycle: hourly                                                                                                                                                                 
  utility_heatpump_daily_consumed_energy:                                                                                                                                         
    source: sensor.nibe_174067_total_consumed_energy                                                                                                                              
    cycle: daily                                                                                                                                                                  

And also I want to be able to see usage of the current day in the dashboard. I am unsure if daily utility meter is constantly updated or only once per day? Can I instead specify hourly and will it then be properly added as a device to the dashboard?

Hi Bortek,

You cannot calculate power by just multiplying the voltage and current. You need the power factor cos(phi) because a heat pump is not a purely resistive load. I would advise, for example, to take a Shelly EM, which can accurately monitor the power and energy of your heat pump.

Well, you are right on spot. Thanks for pointing it out. :slight_smile: Now I know why my calculated heatpumpā€™s Apparent Power S is more than the total Real Power of the whole house (calculated by a Easee power meter).

Since power factor cos(phi) likely vary (all the time, during the day?) for my heatpump and will affect the real power. I presume that it (S=VIcos(phi)) is probably less than apparent power.

Well I asked ChatGPT if I could somehow calculate the power factor and it said that I might be able to find it from the manufacturer. But I have some doubts about it :stuck_out_tongue:

I have already Qubino three-phase power meters in the house one for sauna and one for Hot tub but putting one more for the heatpump will be too difficult. There is actually one already sitting there there but it does not have any interfaces, not even modbus. So no luck with that.

BTW the code I wrote above was not quite correct in terms of syntax and indentations and format to be put in the configuration.yaml. I have now edited it to the ā€œworkingā€ and keeping the I*V values for the reference.

1 Like