Split energy consumption of one entity in more entities based on the device's operating mode?

I have Smappee for monitoring my energy usage of all my devices. One of them is my heat pump that I also read using Modbus.

So, right now in HA I can see if my heatpump is busy preparing hot water, cooling or heating the house. Using smappee I can see the energy consumption.

Now I want HA to split this energy usage in multiple entities, so that I can see how much energy the heatpump is using when it’s operating in “cooling”, “heating”, “hot water” or “other” mode.

My initial thought was that I can use a template sensor to do this.
Something like this:

template:
  - sensor:
      - name: "Heat pump (heating)"
        unique_id: heatpump-heating
        state: >
            {% if states('sensor.heatpump_operating_mode_numeric')|int == 19 %}
            {{ states('sensor.smappee_kwh_heatpump')|float }}
            {% else %}
            {{ states('heatpump-heating') }}
            {% endif %}
        unit_of_measurement: kWh  
        device_class: energy
        state_class: total_increasing

But this won’t work because it will make the template jump to the new kWh value as soon as the heatpump switches back to “heating” mode.

I hope someone here can help me out and tell me how to make this work?

Ok. Never mind :wink:
I managed to make it work using the utility_meter and an automation.

Can you please describe how you did accomplish this as I have exactly the same challenge