One power sensor and two templates ( +/- value)

Hey there,

I’m new to HA and recently added my energy meter into my HA configuration. It works fine overall but I thought it would be nice (and is also needed for the energy dashboard) to differ between grid consumption and grid feed.

I have created a sensor that is receiving data via mqtt from the energy meter. This is the code for this one:

  - sensor:
      name: "Netz"
      unique_id: "grid_power"
      state_topic: "energymeter/serialnumber/parameter"
      unit_of_measurement: "W"
      state_class: "total_increasing"
      device_class: "power"
      value_template: "{{ (value_json.0.p | float(0) + value_json.1.p | float(0) + value_json.2.p | float(0)) | round(0) }} "

The energy meter gives me one value that can be positive (consumption) or negative(feed), so nothing special about this one.

So i tried to create two template sensors, one for positive values and one for negative values. I’ve taken the code from other posts as I wasn’t able to figure out how to code it :sweat_smile:

The two template sensors are called “Netzbezug” (consumption) and “Netzeinspeisung” (feed):

  - sensor:
      - name: "Netzbezug"
        unit_of_measurement: "W"
        state: >
          {% if states('sensor.grid_power')|float(0) >= 0 %}
            {{ states('sensor.grid_power') | float(0) }}
          {% else %}
            0
          {% endif %}
        device_class: power
        state_class: total           
          
      - name: "Netzeinspeisung"
        unit_of_measurement: "W"
        state: >
          {% if states('sensor.grid_power')|float(0) < 0 %}
            {{ -1 * states('sensor.grid_power')|float(0) }}
          {% else %}
            0
          {% endif %}        
        device_class: power
        state_class: total 

The problem is that I’m only getting 0 as a value, even if there is consumption or feed.
I have another template sensor that is displaying the value without bothering if it’s positive or negative (this one is working fine).

Any idea why I’m not getting any value?
Pretty sure it is an mistake or misunderstanding by me.

Thank you in advance!

Should be state_class: measurement for power sensors. “total” is for always increasing sensors, like energy. This goes for all three of your sensors.

Also to get the positive magnitude of a negative number you can do this:

{{ states('sensor.grid_power')|float(0)|abs }}

Thank you very much!

Changed the state_class: measurement for all sensors now.

You mean to put in this {{ states('sensor.grid_power')|float(0)|abs }} instead of
{{ -1 * states('sensor.grid_power')|float(0) }} , right?

But I guess both adjustments won’t affect my problem of not getting a value? :grinning_face_with_smiling_eyes:

Solved it!

Will post the change for the templates later if needed.