Set `last_reset` attribute if energy monitor reset value

Hello,
I have sensor.corridor_energy_monitor_total sensor who display kWh.
I create template sensor with last_reset attribute :

template:
  - sensor:
      - unique_id: energy_monitor_total2
        name: "energy_monitor_total"
        unit_of_measurement: 'kWh'
        state: >
          {{ (states("sensor.corridor_energy_monitor_total") | float) | round(2) }}       
        device_class: energy
        state_class: measurement
        attributes:
          last_reset: >
            {%- if states('sensor.corridor_energy_monitor_total') < states('sensor.energy_monitor_total2') -%}
              {{ now() }}
            {%- else -%}
              {{ '1970-01-01T00:00:00+00:00' }} # or last state of this attribute if exists
            {%- endif -%}

I want to set last value of this attribute or default value (โ€˜1970-01-01T00:00:00+00:00โ€™) if not exists last value in โ€˜elseโ€™ condition.

How can I do it?

1 Like

The measurement state class does not require a last_reset attribute.

See: Sensor Entity | Home Assistant Developer Docs

Also you are just copying the state of another sensor. This is not required either. You can add attributes to the original sensor using customize.

Iโ€™d suggest:

homeassistant:
  customize:
    sensor.corridor_energy_monitor_total:
      device_class: energy
      state_class: total_increasing

It not resolve my problem, because I want to change last_reset attribute if sensor.corridor_energy_monitor_total sensor reset its value.

And as I said:

I know, but last_reset attribute is required by Energy dashboard. I want to use Energy dashboard with my custom sensor.

Nope.

That is only required for a sensor with a state_class of total_increasing. Even then it is updated automatically for you.

If your sensor periodically resets the energy dashboard will take care of this for you if your sensor has the attributes:

      device_class: energy
      state_class: total_increasing

As long as sensor.corridor_energy_monitor_total has those two attributes, and an appropriate unit_of_measurement (Wh or kWh), you can use it with the energy dashboard.

Tnx for information.

I have one more question:
Is it a problem if my sensor resets value at different periods?

Nope. The energy dashboard will recognise a decrease in value as a reset at any time.

An issue only occurs if your sensor goes to 0 when unavailable then reverts to the full previous total. Then that whole total gets added to the recorded energy. This happens a lot with poorly constructed template sensors. e.g.

value โ†’ 0 โ†’ value : add the whole value to the energy total

value โ†’ unknown โ†’ value : add nothing to the total.

So if your energy sensor starts climbing up normally after resetting to zero it will work fine.