Template sensor to track CO2 footprint of appliance

I have sensors that track electricity use, and I’m using the Electricity Maps integration to measure the CO2 intensity of my electricity. I want to combine these to tracks the CO2 footprint of my appliances, i.e. the integral of the power times the CO2 intensity.

I have this sensor, which works more or less, however:

  1. At creation the sensor value is unavailable, I’m not sure why. I would expect it to return 0.
  2. I’d like the sensor value to survive Home Assistant restarts, is this possible?
  3. I’d like the sensor to stay at the current value if there’s a problem such as some of the input sensors being unavailable (e.g. I don’t want the ‘0’ clause to happen)

I currently have the following:

template:
  - trigger:
      - platform: state
        entity_id: sensor.metercupboard_energy
        to:
    sensor:
      - name: "Metercupboard CO2 Footprint"
        unit_of_measurement: "gCO2eq"
        unique_id: 'metercupboard_energy_co2_footprint'
        state: >
          {% if is_number(this.state) and is_number(trigger.to_state.state) and is_number(trigger.from_state.state) and is_number(states('sensor.co2_intensity'))  %}
            {{ (this.state | float(0)) + (trigger.to_state.state | float(0) - trigger.from_state.state | float(0)) * states('sensor.co2_intensity') | float }}
          {% elif is_number(this.state) %}
            (this.state | float(0))
          {% else %}
            0
          {% endif %}

Thanks for the suggestion! A few questions/comments:

  1. I skipped device_class: energy because it’s actually weight (g).
  2. I check the entities used with is_number instead of not in ['unknown', 'unavailable'] because it feels more applicable.
  3. restore_value is not valid for a template sensor, any alternative for this?
  4. Is last_updated not automatically updated?

Thanks

Thanks for the quick reply!

  1. Yes I did
  2. Ok clear
  3. Ok, I’ll consider implementing this or not.
  4. Ok thanks