Help with simple template that check a sensor for a value and does an IF ELSE

Hi,

I have 3 sensors. What I want to achieve is simple. If A = 0 then C - B is my final value else C + A is the final value. I have come up the code below but it’s clearly wrong. Any help would be appreciated.

- name : "active_energy_usage"
    unit_of_measurement: 'W'
    device_class: power
    state_class: measurement
    state: >
    {% if has_value(sensor.powerpalble_powerpal_000491c1', 0) -%}
          {{ [0, states('sensor.inverter_active_power') | round - states('sensor.pv_grid_return') | round] | max }}
    {%- else -%}
          {{ [0, states('sensor.inverter_active_power') | round + states('sensor.powerpalble_powerpal_000491c1') | round] | max }}
    {%- endif %}
  - name: Active energy usage
    unique_id: active_energy_usage
    unit_of_measurement: 'W'
    device_class: power
    state_class: measurement
    state: >
      {% set pwrpal = states('sensor.powerpalble_powerpal_000491c1') | round(0) %}
      {% set inverter = states('sensor.inverter_active_power') | round(0) %}
      {% set pv = states('sensor.pv_grid_return') | round(0) %}
      {{ [0, inverter - pv if pwrpal == 0 else inverter + pwrpal] | max }}

You can test the template by copy-pasting it (4 lines) into the Template Editor.

@123

Thanks Taras. One more question if you will please. I have one more issue if you can help. I would like to return a 0 value for PV sensor irrespective of its value is if PWRPAL reads anything above 0.

Can you help?

If this is what you want:

      {% set pv = 0 if pwrpal > 0 else pv %}

then you can add it just before the last line as shown here:

  - name: Active energy usage
    unique_id: active_energy_usage
    unit_of_measurement: 'W'
    device_class: power
    state_class: measurement
    state: >
      {% set pwrpal = states('sensor.powerpalble_powerpal_000491c1') | round(0) %}
      {% set inverter = states('sensor.inverter_active_power') | round(0) %}
      {% set pv = states('sensor.pv_grid_return') | round(0) %}
      {% set pv = 0 if pwrpal > 0 else pv %}
      {{ [0, inverter - pv if pwrpal == 0 else inverter + pwrpal] | max }}

@123 Thank you so much that worked a treat.

1 Like

You’re welcome!

Please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions.

For more information about the Solution tag, refer to guideline 21 in the FAQ.