How to split a sensor into positive and negative sensors

How to split a sensor that shows positive and negative values into two sensors, one for positive values one for negative values. This is particularly useful for power sensors:

template:
  - sensor:  
      - name: Grid Power In
        unit_of_measurement: Wh
        device_class: power
        state_class: measurement
        state: >
          {% if states('sensor.grid_power') | float(0) >= 0 %}
            {{ states('sensor.grid_power') | float(0) }}
          {% else %}
            0
          {% endif %}
        availability: "{{ has_value('sensor.grid_power') }}"

      - name: Grid Power Out
        unit_of_measurement: Wh
        device_class: power
        state_class: measurement
        state: >
          {% if states('sensor.grid_power') | float(0) <= 0 %}
            {{ states('sensor.grid_power') |float | abs }}
          {% else %}
            0
          {% endif %}
        availability: "{{ has_value('sensor.grid_power') }}"

The Home Assistant Cookbook - Index.

5 Likes

If you prefer to use the UI, the template helper can be used.

If no conversation math is required the filter helper can be used.

yes, or max:

      - unique_id: saldo_totaal_dag_energie_afname
        state: >
          {% set saldo = states('sensor.grid_energy_total')|float(0) %}
          {{[0,saldo]|max}}

power:

 {% set power = states('sensor.netto_verbruik')|int 
 {{[0,power]|min|abs}} # use `abs` to turn the negative power, return to grid, into a positive,

 {{[0,power]|max}}

sweet. I had played around with the filter before, but somehow got the impression it took more from the system than the simple template using min/max/abs

could have been imagination…