Price tracking energy usage dynamic contract

I am trying to make a sensor that tracks how much has been spend on a powerplug this month. The plug gives me the amount of total imported KWH I have another sensor that provides me with the KWH price of that hour. Now i need to make a third sensor that tracks how much money has been spend in total, the thing that is happening is that the amount is just kwh*price. So i get the KWH of al time multiplied with the hourly price, which can be much lower or much higher.

Any help would be appriciated

1 Like

Hi @mikevankan

I’m no guru, but it looks like you want to define a template sensor. See the examples here:

Template Sensors

If you are new to coding, you might try asking ChatGPT. Just be very explicit with what you want, the names of existing sensors, formulas etc.

Best wishes.

I may have something that fits you well.

I use a triggered template sensor

I have a sensor sensor.kamstrup_tpi which reports the kWh and it never resets. It just increases at a certain rate.

And I have a sensor sensor.electricity_price_median which is the current price of electricity.

This sensor then calculates the spend every time the meter reports a new value

- trigger:
    - platform: state
      entity_id: sensor.kamstrup_tpi
  sensor:
    - name: "Electricity Spend"
      unique_id: electricity_spend
      #device_class: monetary
      unit_of_measurement: "DKK"
      state: >
        {% set price = float(states('sensor.electricity_price_median'),0) %}
        {% set meter = float(states('sensor.kamstrup_tpi'),0) %}
        {% if meter > 0 and this.attributes.last is defined %}
           {% set delta = meter - float(this.attributes.last,0) %}
        {% else %}
           {% set delta = 0 %}
        {% endif %}
        {{ '%0.6f'|format( price * delta  ) }}
      attributes:
        last: >
          {% if this.attributes.last is defined %}
            {% set lastlast = float(this.attributes.last,0) %}
          {% else %}
            {% set lastlast = 0 %}
          {% endif %}
          {% set meter = float(states('sensor.kamstrup_tpi'),0) %}
          {% if meter > 0 %}
            {{ meter }}
          {% else %}
            {{ lastlast }}
          {% endif %}

I abuse the attribute part of the template sensor to hold the electricity meter reading from the previous reading. This way I can calculate the incremental consumption. And then I multiply by the price

This is part of the way. You want to accumulate by month.

You then create a Utility Meter Helper. You do that in the UI. Settings → Devices and Services → Helpers tab → Create Helper button. You define the period to be monthly and you use the triggered template sensor as input. And turn on Delta Values in the dialog

And then you have a monthly price.

Hope this helps

This is a great idea. I have done this with an automation storing the last value in an input_number helper. This solution is more elegant.

Hi @KennethLavrsen,

I played with your idea. I have a similar need to track the costs/yield of my wallcharger and solar panels in EUR. Since I use dynamic tariffs, I cannot simply multiply my energy total counter with the tariff.

Based on your idea I came up with my version:

trigger:
  - platform: state
    entity_id: sensor.solis_inverter_energy_today
sensor:
  - name: "Totaalteller test"
    unique_id: <<some_unique_id>>
    icon: "mdi:counter"
    state: >-
      {% set stroomprijs = states('sensor.electricity_price') | float(0) %}
      {% set delta = trigger.to_state.state | float(0) - trigger.from_state.state | float(0) %}
      {% set previous = (this.state if this is defined else 0) | float(0) %}
      {% if delta > 0 %}
        {{ previous + delta * stroomprijs }}
      {% else %}
        {{ previous }}
      {% endif %}

With this approach you do not even have to use attributes.

Brilliant

had not thought about from_state of the trigger

Just noticing a small difference. jeedewee has defined his sensor as accumulating.

Mine shows the spending since last report.

Both can be used but you feed a utility meter differently. Note the “delta values” switch in the utility meter. I am not sure there are any advantages doing it one way or the other. I chose to have mine showing the incremental value because any strange missing value just becomes a 0 and you may have missed a few cents. If there is a spike in the input data the previous value can become 0 and then what?

But the method to calculate the incremental energy using trigger.to_state.state | float(0) - trigger.from_state.state | float(0) is still smarter.

But I think it is best not to add the value with the previous + delta * stroomprijs but just let the sensor be either 0 or the incremental spending. And the summary of cost is then calculated using the utility meter.

thanks for your reply in my thread Spent hours with energy dashboard - how to get monthly costs? - #5 by Stiltjack . I try to setup the template sensor. how did you create the sensor.electricity_price ? Is it a text-helper and the value corresponds to the kwh-price?

example:

As I said in the other thread, I no longer have energy tracking in my HA setup. Going back through my backups, however, this is a sample template:

  - sensor:
      - name: "fridge monthly"
        state: '{{ (states("sensor.tasmota_12_energy_monthly")| float(0) * states("input_number.electricity_rate")| float(0) / 100) | round (2) }}'
        device_class: monetary
        state_class: total_increasing
        unit_of_measurement: "ÂŁ"
        icon: mdi:fridge

As you see, the cost per kwh (taken from my electricity bill) was in an input_number helper to make it easy to change. Energy usage came initially from a tasmota smartplug, with utility meter providing a monthly figure.

In the dashboard I just had an entities card with the current total, which would reset to zero on the first of the month.

Sorry if this is a bit vague - it’s hard to reconstruct six months after removing it.

1 Like

got you, anyway thanks a lot! this should help me to build the template-sensor.

Thanks @KennethLavrsen for your reflection. I also have the feeling that using the previous value may not always be stable. Time will tell I guess. Maybe we can also get a response from the core developers as to what approach they think is more stable and recommended.

Also if you mark the counters with accumulating, it will be included in long-term-statistics. So you can derive from there counters for current, previous, month/day/year etc using a statistics sensor.

Also checked again the utility meter documentation and now I understand the “delta values” option.

Hi Jurgen, thanks for the code and happy to use it in my situation.

I have an additional challenge: reduce the amount of changes. Is it possible to reduce the number of triggers to around once a minute or once per 500 Watts?

template:
  - trigger:
    - platform: state
      entity_id: sensor.electra_netto_cumulatief
    sensor:
    - name: "Kosten totaal electra vandaag"
      unique_id: Kosten_electra_vandaag
      unit_of_measurement: "Eur"
      icon: "mdi:counter"
      state: >-
        {% set stroomprijs = states('sensor.nordpool_inkoopprijs') | float(0) %}
        {% set delta = trigger.to_state.state | float(0) - trigger.from_state.state | float(0) %}
        {% set previous = (this.state if this is defined else 0) | float(0) %}
        {% if delta != 0 %}
          {{ previous + delta * stroomprijs }}
        {% else %}
          {{ previous }}
        {% endif %}



KR
Marco

1 Like

May I ask why it should be necessary to reduce the amount of changes?
Maybe there are other possibilities.

Cheers
Matt

@kleinerhobbit : To reduce the system occupancy (in dashboard graphs)