SOLVED - Calculate cost for individual device cost/kWh

I need help setting up and running a calculation of the cost of an individual device (in this case the dish washer). My aim is to have a sensor that shows the accumulated cost based on the usage of a device, and the corresponding hourly price.

  • What I don’t know is if the should be done by an automation that updates every time the state of the device wattage updates, and if this can take into account if for example the device runs at 500 watts for one minute or if it runs at 500 watts for 1 hour.

  • Or if this is better done via some sort of multiplication of the two graphs and then added to a storage sensor (cost.dishwasher_total) as a value (([wattage] times [hourly price]) plus [cost.dishwasher_total])

The sensors are
sensor.outlet_dishwasher_current_power


Image 1. “The current power usage in watts

sensor.electricity_price_home


Image 2. “price/hour (in SEK)

Help with this and the creation of corresponding automation or script would be greatly appreciated.
Peace :dove: :v:

4 Likes

This ended up to be (one, not the only) the working solution for me;

Create one sensor that accumulates the wattage over time. Then create a hourly utility sensor from the accumulation sensor. Then multiply the price/hour-sensor with the utility sensor in the configuration-yaml file. Profit.

For my household/background information

Summary

My household have hourly based rates/electricity price. This means that the price of the electricity changes every hour, every day.

For example;

  • 00:00 - 01:00 [currency]1/kWh
  • 01:00 - 02:00 [currency]2/kWh
    …and so on.

I have a sensor that shows the now (like only right not) current electricity price. This sensor is created by the Home Assistant integration with my electricity company (Tibber). Lets call this sensor;

sensor.current_kwh_price
Unit of measurement: [currency]/kWh

The device in question

Summary

A smart plug, a refrigerator, in wall smart switch with power metering, it doesn’t matter really…
This we call “Device A”. Device A has power metering that shows the current wattage usage in real time [watts]. Right here it’s called “Current Power”.

sensor.device_a_watt
Unit of measurement: W

1. Create a sensor that accumulates the wattage over time

Summary

This is primarily a helper for the the next sensor, but can be used in different ways later on

Create a Riemann sum integral sensor in Settings\Devices & Services\Helpers\Create helper\ Riemann sum integral sensor.

Here you use the original wattage sensor
sensor.device_a_watt

  • Left Riemann sum
  • kilo
  • hours

This will result in;

sensor.accumulated_wattage_device_a
Unit of measurement: kWh

2. Create a utility sensor that accumulates per hour

Summary

Create a utility sensor in Settings\Devices & Services\Helpers\Create helper\Utility sensor

Here you use the sensor from the last step;
sensor.accumulated_wattage_device_a

  • Hourly

This will result in;

sensor.accumulated_kW_per_hour_device_A
Unit of measurement: kWh

3. Create a new sensor by multiplying sensor values

Summary

Open your configuration.yaml file in an editor. I use VS Code.
Make a backup copy of the file, save it somewhere good.

If you have sensors: already in the file, add from - platform: template.
If this is your first manually added sensor, just paste the code below, and change the names of the sensors accordingly.

Make sure that the indentations are correct

Please insert the currency of your liking into the code without the bracket signs
This is a bracket sign: [
and this also: ]

sensor:
  - platform: template
    sensors:
      cost_hourly_device_a:
        friendly_name: "The cost for sensor called Device A, [Your-selected-currency] per hour"
        unit_of_measurement: "Your-selected-currency"
        value_template: "{{ (states('sensor.accumulated_kW_per_hour_device_A') | round (0)) * (states('sensor.current_kwh_price') | round (0))}}"

this will create the sensor called;

sensor.cost_hourly_device_a
unit_of_measurement: Your-selected-currency

4. Save

Summary

Save the configuration.yaml file.
Then check if its saved, again.

5. Check Configuration in Developer Tools

Summary

If there are errors, read them, use your wits, then google search, then ask a friend, then read the error description again, then double check the code, then you will find the spelling mistake you did, correct it, the press the “Check config-button” again, and it will turn green.

Press Restart

6. Profit

Summary

The sensor
sensor.cost_hourly_device_a
should now be usable in Home Assistant.
Test it by going to Developer Tools\States, and search in the “Entity” field.
Please make sure to give it some time to rack up some watts before being upset for it “not working”.

image


Hash tags and search words

How do I create a sensor that shows cost per device?
How do I calculate cost per device?
How do I show cost for a device if I have price per hour/hourly?

Configuration Community Guides

6 Likes

Thank you, this is what I was wrecking my brain with. Simple and effective. Thanks! I ended up with the following:

template:
  - sensor:
      - name: Effective Electricity Price
        unique_id: effective_electricity_price
        unit_of_measurement: "€/kWh"
        state: >
            {% set override = float(states('input_number.electricity_price_override')) %}
            {% if override > 0 -%}
              {{ states('input_number.electricity_price_override') }}
            {%- else -%}
              {{ states('sensor.nordpool_ee') }}
            {%- endif %}
  - sensor:
      - name: 'House Energy Cost'
        unique_id: house_energy_cost
        unit_of_measurement: €/h
        state: >-
          {{ states('sensor.house_power')|float / 1000 * states('sensor.effective_electricity_price')|float(0) }}
  - sensor:
      - name: 'Car Charging Cost'
        unique_id: car_charging_cost
        unit_of_measurement: €/h
        state: >-
          {{ states('sensor.car_charger_power')|float / 1000 * states('sensor.effective_electricity_price')|float }}
  - sensor:
      - name: 'Car Charging Cost Hourly'
        unique_id: car_charging_cost_hourly
        unit_of_measurement: €
        state: >-
          {{ states('sensor.car_charger_energy_hourly')|float * states('sensor.effective_electricity_price')|float }}
  - sensor:
      - name: 'Car Charging Cost Daily'
        unique_id: car_charging_cost_daily
        unit_of_measurement: €
        state: >-
          {{ states('sensor.car_charger_energy_daily')|float * states('sensor.effective_electricity_price')|float }}
  - sensor:
      - name: 'Car Charging Cost Monthly'
        unique_id: car_charging_cost_monthly
        unit_of_measurement: €
        state: >-
          {{ states('sensor.car_charger_energy_monthly')|float * states('sensor.effective_electricity_price')|float }}
  - sensor:
      - name: 'Car Charging Cost Yearly'
        unique_id: car_charging_cost_yearly
        unit_of_measurement: €
        state: >-
          {{ states('sensor.car_charger_energy_yearly')|float * states('sensor.effective_electricity_price')|float }}

Hmm, I celebrated too quickly. While the hourly sensor makes sense, I am struggling to get totals for a day, week, month, year… With my approach above, the totals keep changing every hour and can decrease, which obviously isn’t correct. Any thoughts?

1 Like

I’ll try to take a look at my setup within the next 24h. Currently monitoring my latest offspring conducting bicycle trials at the local sand pit (playground)

1 Like

Hi
I hope you figured it out, but if not;
Helper\New\Utility meter\ Meter reset cycle: week

Not sure how the entire setup of yours looks like, but I wasn’t able to get it working by having utility meters for periodic consumption (kWh) and then using template sensors to calculate costs for each of those periods (€).

I tried so many different approaches, so I might misremember, but I think I also tried using the cost sensor as a Utility Meter input sensor, but it was problematic as well.

For measuring consumption in kWh, I do use the utility meter helpers.

For costs, however, I ended up doing it not as elegantly, but for now it works. I have input number fields for each period I want to measure and updating them at the end of each hour/day/etc…

alias: "Update Car Charging Costs "
description: ""
trigger:
  - platform: time_pattern
    minutes: "59"
    seconds: "55"
    id: hourly
  - platform: time_pattern
    minutes: "59"
    seconds: "55"
    id: daily
    hours: "23"
condition: []
action:
  - choose:
      - conditions:
          - condition: trigger
            id: hourly
        sequence:
          - service: input_number.set_value
            data:
              value: >-
                {{ states.input_number.car_charging_cost_daily.state | float +
                states.sensor.car_charging_cost_hourly.state | float }}
            target:
              entity_id: input_number.car_charging_cost_daily
          - service: input_number.set_value
            data:
              value: >-
                {{ states.input_number.car_charging_cost_monthly.state | float +
                states.sensor.car_charging_cost_hourly.state | float }}
            target:
              entity_id: input_number.car_charging_cost_monthly
      - conditions:
          - condition: trigger
            id: daily
        sequence:
          - service: input_number.set_value
            data:
              value: 0
            target:
              entity_id: input_number.car_charging_cost_daily
          - condition: template
            value_template: "{{ (now() + timedelta(days=1)).day == 1 }}"
          - service: input_number.set_value
            data:
              value: 0
            target:
              entity_id: input_number.car_charging_cost_monthly
mode: single

And here is how I display it:

And then for cross-checking and deeper dives, I’ve used the workaround in Energy Dashboard, adding my car charger as “gas consumption” source. This gives me daily breakdowns of consumption and costs:

I found another way to create a cost utility meter for individual devices.
Create or identify the sensor with your active energy tariff.

Then create per device that you want to calculate the electricity costs the following triggered sensor. This sensor triggers every 5 seconds and loads the Active Power from your device in Watts. To transform this to kWh you need to divide its value by 720.000. This value is multiplied by your active tariff.
Since by design a utility meter will not update if the state of this sensor does not change I add a very small random number to the calculated value so even if the consumption in Watt stays equal the state of the created sensor varies.

  # Cost electricity per 5 seconds sensor
  - trigger:
      - platform: time_pattern
        seconds: '/5'
    sensor:
      unique_id: electricity_cost_device_5sec
      device_class: energy
      unit_of_measurement: "€"
      state: "{{ ((states('YOUR_SENSOR_active_power') | float / 720000) * (states('YOUR_SENSOR_WITH_energy_electricity_active_tarif') | float)) + (range(1,99) | random)/1000000000  }}"  

The above sensor is now the cost for the electricity consumption for 5 sec.
Next create a Utility Meter and use this new created sensor as input. Important is to enable the option Delta values so each 5 seconds the sensor updates, the utility meter will add the new value to the existing.
You can choose yourself to reset the cycle per day/month/year whatever you need.
It is as simple as this.

I did several tests over time and the deviation from the internal cost calculation of the grid consumption is less than 0.5%.

2 Likes

This seems like a pretty nice solution!

1 Like

Could you elaborate a bit more on have to implement this.
Don’t quit get where to add the YAML to my configuration

Hi Jesper,
This triggered sensor should be put in the configuration.yaml
After that restart HA so the sensor will be loaded

I hope you don’t have alot of these sensors in your config.yaml
Have you considered the amount of entries ( processed and written to your DB / Disk ) , per template-sensor ? ( beside the already processed and stored values from the orig sensors )
Im thinking 1 reason most people is interested in energy-usage, is to save energy / money , so sometimes it seems like they create more usage and warn-out to their hardware , not to mention reducing performance , for other important tasks

Normally , if people have a variable time-cost per kWh, it’s calculated/debit per hour ( or sometimes some actually (without knowing it, are paying the average over time)

So most likely, if people count the cost , for a particular device ( kWh / hour ) they get pretty close to the accurate cost / usage , counting and calculating every 5 seconds ( for 1 device ), and store this in DB , along with the already stored values from the entities, doesn’t sounds logic to me. In particular not for people who pays a fixed / or hourly price.

Depends highly on your platform. I run on HA on a Debian server and have about 940 sensors from which 120 are template sensors. Not for energy consumption but also for several multimedia systems, satellite calculations etc etc. Some update each 5 seconds some every 30 min.
No performance issues at all and the data altering in the database is peanuts compared to the analytics systems I run. That is exactly what databases are made for. A database doesn’t write each transaction immediately to disk but processes in memory first
The template sensor above is used for a certified energy meter and needs to do the billing quite accurate.

Not sure what you mean depends on the Platform

This above i doubt is platform depended !

is that your definition of platform ?

You know quite some people runs HA on i.e a sd-card (and with a default size of disk-space) , in a Device that most likely have i.e 2GB ram, and, if you haven’t noticed, are struggling with DB size, performance and other related issues, many times do to the fact that they don’t have deep knowledge of how a system like HA works.
I just feel one should have this in mind, when suggesting solutions, which in fact is Not Standard Behavior, and does have a substantial impact, on both writings , memory uses etc. You present your solution like people could create 10th of such template-sensor, for each of their Power-sensors ( which ofcause they could , not knowing the consequences )
Beside these sensors ( do the math , every 5 seconds , 24 hours / day , even if no power-usage occur )

I’ve tried to get this to work but it doesn’t seem to work with my configuration.yaml - any pointers to where I’m going wrong?

Error is based on formatting

bad indentation of a mapping entry (141:3)

 138 | 
 139 | 
 140 | # Cost electricity per 5 seconds  ...
 141 |   - trigger:
---------^
 142 |       - platform: time_pattern
 143 |         seconds: '/5'

When I play with the formatting to get it to be accepted with the green tick, Dev Tools rejects the configuration when checked.